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.
Tweet
2 comments:
Incredibly Useful.
I was looking for something like this, and I didn't even know it.
Thanks.
Post a Comment