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.
-
- ServiceController[] services = ServiceController.GetServices();
-
-
- foreach (ServiceController service in services)
- {
- Console.WriteLine("Name: " + service.ServiceName + ", Status:" + service.Status);
- }
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:
-
- foreach (ServiceController service in ServiceController.GetServices())
- {
- service.Start(); // To start the service
- service.Pause(); // To pause the service
- service.Continue(); // To start the paused service
- service.Stop(); // To stop the service
- }
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.