문제

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
}
도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top