How to check the status of windows service using c#

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..!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: