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:

// Get all installed services
var startedServices = from sc in ServiceController.GetServices()
    where sc.Status == ServiceControllerStatus.Running
    select sc;
Console.WriteLine("And the installed services are:");
// now lets iterate thru all the started services
foreach (ServiceController startedService
    in startedServices.ToList())
{
    Console.WriteLine("  " + startedService.ServiceName +
        ": " + startedService.DisplayName);
}

The major (and only) drawback when using LINQ is that it’s only available in .net framework 3.5.

For more on LINQ see also: ScottGu’s introduction to LINQ (focused on SQL LINQ), Introducing Microsoft LINQ, LINQ Pocket Reference, Language Integrated Query in C#2008Programming Microsoft LINQ or the LINQ page in Wikipedia.


Posted

in

by

Tags:

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from try {} except

Subscribe now to keep reading and get access to the full archive.

Continue reading