Search code examples
c#.netwindows-services

ServiceController.ServiceName doesn't throw InvalidOperationException when the Windows service is not installed


According to the documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller.servicename?view=dotnet-plat-ext-7.0#exceptions

The ServiceController.ServiceName will throw an InvalidOperationException if "The service was not found."

But running this code, it runs without throwing an exception:

var serviceController = new ServiceController();
serviceController.ServiceName = "Not.Existing.Service";

I, personally, don't believe this check on the service status happens upon setting the ServiceName (on the creation of the ServiceControler object). But the documentation is not clear when the exception is thrown exactly on this property.

There's also a possibility that the exception is thrown on getting the value from the ServiceName, I tried the following scenario:

  1. Installed a service
  2. Ran the code (below)
  3. Paused the debugger on line 3
  4. Uninstalled the service
  5. Continued running the code

No exception occurred!

/*1*/ serviceController.ServiceName = "Existing.Service";
/*2*/ serviceController.Start();
/*3*/ var serviceName = serviceController.ServiceName;

I also found other questions (this one) that none of the answers mention this property when checking whether a Windows service is installed or not.

Note: my problem is not trying to figure out how to check whether a Windows service is installed or not, but to understand when the exception is thrown on the ServiceName property.


Solution

  • You'll need to use the constructor with string argument to make (an attempt to make) a link with an existing service.

    Initializes a new instance of the ServiceController class that is associated with an existing service on the local computer.

    The constructor will not throw an exception in case the service does not exist, but accessing that ServiceName property get will throw one as documented.

    Below example throws that exception.

    var serviceController = new ServiceController("Not.Existing.Service");
    var serviceName = serviceController.ServiceName;  // << Exception thrown.