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
}
Best Solution
Look at solution below...
It doesn't appear that you can...From the docs:
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
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