Check the Status of a Windows Service in C#

If you have an application that has a dependency on a Windows service, your application may need to be aware of the status of the service. Luckily, the .Net Framework makes this very easy for us to do.

Here’s how you can retrieve the status of a service:

var serviceName = "IISADMIN";
var sc = new ServiceController(serviceName);

Console.WriteLine("Status: {0}", sc.Status);

If you need your application to wait for a particular status, that’s very easy, too!

Console.WriteLine("Blocking until service is running...");
sc.WaitForStatus(ServiceControllerStatus.Running);

Note that WaitForStatus only blocks when the status doesn’t match the value provided. In other words, if the service in the above example is already running, it will not block.

More information about the ServiceController class can be found here.

Advertisements

Leave a comment

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s