ServiceController Class In C#

Introduction
 
In this blog we will discuss what is ServiceController Class in C# and its usage. Here we will discuss how to  get list Windows Services installed in the machine. We can also check a service is installed or not and also check status of service. Let’s start:
 
Using Code
 
The ServiceController is the component of the system that controls starting, pausing, stopping, and continuing services in the system. It also starts and stops (loads and unloads) services except device drivers. This class available in System.ServiceProcess namespace. By default it doesn’t add to project – so we need to add it explicitly by right click on project -> choose “Add Reference” -> type “System.ServiceProcess”. 
 
Next we will discuss how to get list of Windows Service using ServiceController class.
 
Following code-snippet defines how to fetch all windows services. GetServices() is a static method defined ServiceController class which returns all the services on the local computer except device driver services. Next it is loop over ServiceController[] and get all information about the service. Here we used ServiceName property to get service name and Status property to get status of service whether it is running, stopped or paused. 
  1. // Get list of Windows services  
  2. ServiceController[] services = ServiceController.GetServices();  
  3.   
  4. // Looping over service and get their name  
  5. foreach (ServiceController service in services)  
  6. {  
  7.        Console.WriteLine("Name: " + service.ServiceName + ", Status:" + service.Status);  
  8. }  
Output
 
 
                                          Figure 1: List of all Windows Service
 
Note: All the services you are seeing here, you will get same services when you type ”services.msc” in Run command window(Windows Key + R).
 
Secondly we can start, pause and stop the services by programmatically. Here is the code:
  1. // Start, Pause and Stop the service  
  2. foreach (ServiceController service in ServiceController.GetServices())  
  3. {  
  4.      service.Start(); // To start the service 
  5.      service.Pause(); // To pause the service 
  6.      service.Continue(); // To start the paused service
  7.      service.Stop();  // To stop the service
  8. }  
Conclusion
 
In this blog we discussed about what is ServiceController class in C# and its usage. We learn how to get list of Windows Services installed in a machine and service status. And also we discussed how to start, pause and stop the windows service programmatically. 
Hope it helps.