C# code to check status of a windows service
Below is the C# code which return the status of a windows service running on a machine/server on passing correct name.
One use case of it is that if we want to monitor some specific services which are critical to operation, we can schedule our application to check the status of the specific service/services and if it's ha stopped, we can do certain action like sending an email to concern people so that corrective action can be taken.
Include using System.ServiceProcess; reference in your application.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static String GetWindowsServiceStatus(String SERVICENAME)
{
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Below is the sample test result:
Hope it would be helpful..!!