jQuery and ASP.NET

March 3, 2010

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.

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Programmatically determine if a Windows Service is running and stop it"
  1. Anonymous said...
    March 4, 2010 8:16 PM

    Incredibly Useful.

  2. necr0 said...
    March 8, 2010 8:04 AM

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

    Thanks.

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions