Programmatically determine if a Windows Service is running and stop it

The ServiceController class makes it easy to retrieve information about a windows service and manipulate it. Here’s some code. Before running this example, make sure you have added a reference to System.ServiceProcess

C#

static void Main(string[] args)
{
try
{
ServiceController controller = new ServiceController("SERVICENAME");

if (controller.Status.Equals(ServiceControllerStatus.Running)
&& controller.CanStop)
{
controller.Stop();
Console.WriteLine("Service Stopped");
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

VB.NET

Shared Sub Main(ByVal args() As String)
Try
Dim
controller As New ServiceController("SERVICENAME")

If controller.Status.Equals(ServiceControllerStatus.Running)_
          AndAlso controller.CanStop Then
controller.Stop()
Console.WriteLine("Service Stopped")
End If
Console.ReadLine()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub

Make sure you have permission to stop the service or else you will get an exception.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Anonymous said...

Incredibly Useful.

necr0 said...

I was looking for something like this, and I didn't even know it.

Thanks.