Checking for an unregistered/missing service

How can I use ServiceController to tell me if a service has been registered or not? In the code fragment below, the check for a null DisplayName results in a System.InvalidOperationException.

Is there a straightforward way of doing this that I'm completely missing?

ServiceController sc = new ServiceController("TestService");

if (sc.DisplayName == null)
{
     // unregistered or missing service
}
13.10.2009 15:11:04
1 ОТВЕТ
РЕШЕНИЕ

Look at solution below... It doesn't appear that you can...

From the docs:

You can use the ServiceController class to connect to and control the behavior of existing services.

Which reads like services must already be registered in order for the ServiceController to work with them.

I guess you could simply catch the exception (indicating the service doesn't exist), but that doesn't seem to be truly exceptional does it?

Solution:

Use

var services = ServiceController.GetServices(machineName)

and search the array for your needed services. If you're just working on your local box you can omit the machineName argument.

http://msdn.microsoft.com/en-us/library/s21fd6th.aspx

3
13.10.2009 15:28:47
Excellent! Thank you very much. :)
Talvalin 13.10.2009 15:37:13