The WebClient Windows Service is installed and set to Manual by default; due to my customer's IT restrictions I am unable to change this to Automatic.

When the service is stopped and I try to access files with Directory.EnumerateDirectories I get a the exception:

An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

Additional information: Could not find a part of the path '\mysever\myfolder'.

When the WebClient service is started this works fine.

Accessing the path using Explorer works fine as the WebClient service is started as part of this request.

From code, how can I tell Windows that I want to access the WebClient service so it should start it?

I have the following (working) code, but I am unsure if this requires Administrator permission or if there is any better way to do this:

using (ServiceController serviceController = new ServiceController("WebClient"))
{
    serviceController.Start();
    serviceController.WaitForStatus(ServiceControllerStatus.Running);
}

Effectively all I want to do is to execute the command net start WebClient, is the above code the cleanest way to do this and is there any security restrictions I need to be aware of in a locked down environment?

I have checked the MSDN for ServiceController.Start Method and it doesn't seem say if users must be administrator or not.

有帮助吗?

解决方案

You need administrative privileges.

You can test this out with the below code in a console application on a computer with the WebClient service turned off. Running without administrative privileges gives you "cannot start service on computer '.'"

static void Main(string[] args)
{
    string serviceToRun = "WebClient";

    using (ServiceController serviceController = new ServiceController(serviceToRun))
    {
        Console.WriteLine(string.Format("Current Status of {0}: {1}", serviceToRun, serviceController.Status));
        if (serviceController.Status == ServiceControllerStatus.Stopped)
        {
            Console.WriteLine(string.Format("Starting {0}", serviceToRun));
            serviceController.Start();
            serviceController.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 20));
            Console.WriteLine(string.Format("{0} {1}", serviceToRun, serviceController.Status));
        }
    }

    Console.ReadLine();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top