Check if a service is installed with ServiceController using LINQ

If you want to check if a specific NT Service is installed you will need to use the ServiceController class (from System.ServiceProcess). The first problem you will encounter is that the ServiceController has no static method, that would return a Boolean, specifying if the service is installed or not (e.g. ServiceController.IsInstalled(‘MyService’);) – so, to solve this you need to fetch the list of all installed services, using the static method ServiceController.GetServices(), which returns an array of ServiceController[], and then iterate thru all the elements to see if “MyService” is on that list. Now, this is not a problem, is just too much code for such a simple task. If you use LINQ things are simple: basically you will iterate thru the list, but in a much focused and simple way.

var temp = from sc in ServiceController.GetServices()
where sc.ServiceName == "MyService"
select sc;
// temp.Count() is 0 if the service is not installed
Boolean isInstalled = temp.Count() != 0;

If you want to manipulate the service (if installed, obviously), you don’t need to instantiate a new ServiceController(servicename), as the LINQ query returned a ServiceController ready to go. Add the following lines to the example:

if (isInstalled)
{
ServiceController myController =
// the LINQ query only returns one element - we can use First<>()
temp.First();
Console.WriteLine("Service is installed and " +
myController.Status.ToString());
if (myController.Status == ServiceControllerStatus.Stopped)
{
Console.WriteLine("Starting the service...");
myController.Start();
}
}
else
{
Console.WriteLine("The service is not installed");
}

[ad#468×60]

You can change this LINQ query to search for any of the ServiceController’s properties. The following example returns the list of all started services: