Managing Windows Services

It may happen that you wish to connect to and control the behavior of a Windows Service – programatically. There’s a .NET class called ServiceController just to do that. It represents a Windows service and allows you to connect to a running or stopped service, manipulate it, or get information about it. You will most likely use the ServiceController component in an administrative capacity. For example, you could create a Windows or Web application that sends custom commands to a service through the ServiceController instance. This would be useful, because the Service Control Manager (SCM) Microsoft Management Console snapin does not support custom commands.

Here’s an example to check the status of the Telnet Windows Service and start/stop it as needed:

Dim sc As New ServiceController(“Telnet”)< ?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

?

If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then

sc.Start()

Else

sc.Stop()

End If

?

sc.Refresh()

The ServiceController class can also be used to manage services on another machine (by specifying the MachineName property). The ServiceController?class requires the System.ServiceProcess namespace which you may need to add a reference to.