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.


Bookmark this link on del.icio.us (saved by 0 users)

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

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 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal