views:

79

answers:

4

How do I restart a currently running service in C#.

+1  A: 

Use the ServiceController class.

SLaks
+2  A: 

You can use ServiceController. Example here.

driis
Just for clarification: This sample only works if the service is not stopped. See another user's problem with it: http://stackoverflow.com/questions/3309990/cannot-restart-a-service-c/
0xA3
+1  A: 
ServiceController _ServiceController = new ServiceController([NameService]);
if (_ServiceController.ServiceHandle != null) 
{
     _ServiceController.Stop();
     _ServiceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds([Time]));

     _ServiceController.Start();
     _ServiceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds([Time]));
}
Ph.E
+1  A: 

You'll also want to make sure the user has the proper authentication access (UAC control) on the system. If they don't have the proper access, you'll wind up with an exception in code.

Richard B
Yeah, I included a manifest for UAC.
fryguybob
It becomes a bit trickier than just offering a Manifest file and using MT to bind the manifest to the exe... you have to also account for the limited accounts, which to date, I haven't been able to accomplish. I've created a management taskbar app to manage the windows service, and then always instructed the user to "startup" the service before they can configure anything, and then built the service in a fashion that it can always startup, and use WCF services via named pipes to administer them.
Richard B