Home > other >  ServiceController.ServiceName doesn't throw InvalidOperationException when the Windows service
ServiceController.ServiceName doesn't throw InvalidOperationException when the Windows service

Time:12-30

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 a 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.

CodePudding user response:

If you look at the source code here you will see when this exception is thrown. There are several opportunities for ServiceController to throw this exception on the service name. Specifically, look in the private void GenerateNames() definition. This function is only called in the getters for ServiceName and DisplayName and that's when you'll probably encounter this exception.

CodePudding user response:

If you read this code, it is clearly mentioned that it does not throw exceptions for invalid service names (It does only validation check) on the setter of ServiceController's ServiceName

CodePudding user response:

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.                      
  • Related