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, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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.