简体   繁体   中英

(Re)Starting a Windows Service from out of my C# code does not work

To update my self-written Windows Service , I wrote a C# program that stops the service, copies the new DLLs and then restarts it.

My first approach was the following:

ServiceController service = new ServiceController(serviceName);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// (...) copy the dll files
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);   

While stopping the service worked, the start method produced the following error:

Cannot start service FOVEA Service Debug on computer '.'.   
at System.ServiceProcess.ServiceController.Start(String[] args)    at
System.ServiceProcess.ServiceController.Start()

Running my update program as Administrator made no difference.

So I tried to start/stop the service in the command line via net start/stop service which worked perfectly and I changed my C# program to the following:

Process p = Process.Start("net", "stop \"" + serviceName + "\"");
p.WaitForExit();
p = Process.Start("net", "start \"" + serviceName + "\"");
p.WaitForExit(); 

Like before, stopping the service worked. The call of net start service however ouputted

The service is not responding to the control function
more help is available by typing NET HELPMSG 2186

The service is installed for the local logged in user (Administrator) but I don't see why net start works from the command line but not out of the code. I also tried the following:

  • Set up full permissions for my update program for user NETWORK SERVICE
  • Started the process with p.StartInfo.Verb = "runas"
  • Changed the p.StartInfo.WorkingDirectory to Environment.SystemDirectory
  • Changed the p.MachineName to Environment.MachineName
  • Let the thread sleep for 5 seconds after stopping the service

But nothing seemed to make any impact.

Any ideas how to get what I want? Thanks in advance for your help.

Try this way :

ServiceController sc = new ServiceController(svr_name);
if (sc.Status != ServiceControllerStatus.Stopped)
{
    sc.Stop();
    sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
}

Put some exception handling to avoid error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM