Check if a Windows Service is up through C#


We have a class called ServiceController in C#. This class helps us to query the windows service. For using this class, we have to use the following imports.

using System;
using System.ServiceProcess;
using System.Linq;

Below are a few functions related to windows services.

Function 1 : Checks if a Windows Service exists

public static bool ServiceExists(string ServiceName)
{
    return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(ServiceName));
}

Function 2 : Checks if a Windows Service is running

public static bool ServiceIsRunning(string ServiceName)
{
    ServiceController sc = new ServiceController
    {
        ServiceName = ServiceName
    };

    if (sc.Status == ServiceControllerStatus.Running)
    {
        return true;
    }
    else
    {
        return false;
    }
}

To avoid any possible exceptions, it is good to check if the service exists before checking if the service is running.

That’s all folks!
Thank you!

Leave A Comment

Your email address will not be published. Required fields are marked *