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:
- Installed a service
- Ran the code (below)
- Paused the debugger on line 3
- Uninstalled the service
- 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.