19.2. Controlling a Service
Problem
You need to programmatically manipulate a service that your application interacts with.
Solution
Use the System.ServiceProcess.ServiceController
class to control the service. ServiceController
allows you to interact with an existing service and to read and change its properties. In the example, it will be used to manipulate the ASP.NET State Service. The name, the service type, and the display name are easily available from the ServiceName, ServiceType
, and DisplayName
properties:
ServiceController scStateService = new ServiceController("COM+ Event System"); Console.WriteLine("Service Name: " + scStateService.ServiceName); Console.WriteLine("Service Type: " + scStateService.ServiceType.ToString()); Console.WriteLine("Display Name: " + scStateService.DisplayName);
The ServiceType
enumeration has a number of values, as shown in Table 19-2.
Table 19-2. The ServiceType enumeration values
Value | Description |
---|---|
| Service that serves a hardware device |
| Driver for the filesystem (kernel level) |
| Service that communicates with the desktop |
| Low-level hardware device driver |
| Driver for identifying filesystems on startup |
| Win32 program that runs as a service in its own process |
| Win32 program that runs as a service in a shared process such as SvcHost |
One useful task is to determine a service's dependents. The services that depend on the current service are accessed through the DependentServices ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.