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

Shaul Behr picture Shaul Behr · Dec 29, 2010 · Viewed 49.7k times · Source

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?

Answer

Aliostad picture Aliostad · Dec 29, 2010

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);