views:

47

answers:

1

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
}
+3  A: 

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

Jason Punyon
Excellent! Thank you very much. :)
Talvalin
@Talvalin: No problem
Jason Punyon