How to check if a windows service is installed in C#

I've written a Windows Service that exposes a WCF service to a GUI installed on the same machine. When I run the GUI, if I can't connect to the service, I need to know if it's because the service app hasn't been installed yet, or if it's because the service is not running. If the former, I'll want to install it (as described here); if the latter, I'll want to start it up.

Question is: how do you detect if the service is installed, and then having detected that it's installed, how do you start it up?


Solution 1:

Use:

// add a reference to System.ServiceProcess.dll
using System.ServiceProcess;

// ...
ServiceController ctl = ServiceController.GetServices()
    .FirstOrDefault(s => s.ServiceName == "myservice");
if(ctl==null)
    Console.WriteLine("Not installed");
else    
    Console.WriteLine(ctl.Status);

Solution 2:

You could use the following as well..

using System.ServiceProcess; 
... 
var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);

Solution 3:

Actually looping like this:

foreach (ServiceController SC in ServiceController.GetServices())

may throw Access Denied exception if the account under which your application is running doesn't have rights to view service properties. On the other hand, you can safely do this even if no service with such name exist:

ServiceController SC = new ServiceController("AnyServiceName");

But accessing its properties if service doesn't exist will result in InvalidOperationException. So here's a safe way to check if a service is installed:

ServiceController SC = new ServiceController("MyServiceName");
bool ServiceIsInstalled = false;
try
{
    // actually we need to try access ANY of service properties
    // at least once to trigger an exception
    // not neccessarily its name
    string ServiceName = SC.DisplayName;
    ServiceIsInstalled = true;
}
catch (InvalidOperationException) { }
finally
{
    SC.Close();
}