Updated on Kisan Patel
To programmatically start and stop a service that your application interacts with, you need to use the System.ServiceProcess.ServiceController
class.
ServiceController allows you to interact with an existing service and to read and change its properties.
To start and stop service, first you need to make a reference to System.ServiceProcess
as shown in below screenshot:
Namespace:
using System.ServiceProcess;
The following example uses the ServiceController
class to check the current status of the World Wide Web Publishing Service.
class Program { static void Main(string[] args) { ServiceController scStateService = new ServiceController("World Wide Web Publishing Service"); Console.WriteLine("The World Wide Web Publishing Service status is currently set to {0}", scStateService.Status.ToString()); Console.ReadKey(); } }
Output of the above program…
If a service is stopped, it can be started with the Start
method. First, check if the service is stopped, and then, once Start has been called on the ServiceController
instance, the WaitForStatus
method should be called to make sure that the service started.
// If it is stopped, start it. TimeSpan serviceTimeout = TimeSpan.FromSeconds(60); if (scStateService.Status == ServiceControllerStatus.Stopped) { scStateService.Start(); // Wait up to 60 seconds for start. scStateService.WaitForStatus(ServiceControllerStatus.Running, serviceTimeout); } else if (scStateService.Status == ServiceControllerStatus.Paused) { if (scStateService.CanPauseAndContinue) { scStateService.Continue(); // Wait up to 60 seconds for running. scStateService.WaitForStatus(ServiceControllerStatus.Running, serviceTimeout); } } Console.WriteLine("Status: " + scStateService.Status);
// To stop the service. if (scStateService.CanStop) { scStateService.Stop(); // Wait up to 60 seconds for stop. scStateService.WaitForStatus(ServiceControllerStatus.Stopped, serviceTimeout); } Console.WriteLine("Status: " + scStateService.Status);