How to start or stop a Windows Service using C#


We can start, stop, pause, continue and refresh a service using Start, Stop, Pause, Continue, and Refresh methods.  Close method disconnects this ServiceController instance from the service and frees all the resources that the instance allocated.

The following code snippet checks if a service is stopped, start it; otherwise stop it.

Let's say, you have a service named "MyServiceName". First you create a ServiceController object and then call its Start or Stop methods to start and stop a windows service.

ServiceController service = new ServiceController("MyServiceName");

if ((service.Status.Equals(ServiceControllerStatus.Stopped)) ||

    (service.Status.Equals(ServiceControllerStatus.StopPending)))

    service.Start();

else    service.Stop();


ServiceController class also have Pause, Continue, and Refresh methods to pause, continue, and refresh a windows service.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.