How to start and stop windows services programmatically
This short code snippet shows how you can access the status of any windows services using C# or VB.NET. Also, it is easy to start and stop windows services programmatically.
Introduction
This short code snippet shows how you can start and stop windows services and also how to find the current status of any windows services.System.ServiceProcess.ServiceController class
You can use the .NET class System.ServiceProcess.ServiceController to work with the windows services.
Include the namespace in the top of your class:
VB.NET
Imports System.ServiceProcess
C#
using System.ServiceProcess;
Create an instance of the class:
VB.NET
dim controller as new ServiceController
C#
ServiceController controller = new ServiceController();
See the following code which gets the status of the IIS Admin service. Also, you can start and stop the service using this class.
VB.NET
controller.MachineName = "."
controller.ServiceName = "IISADMIN"
dim status as string = controller.Status.ToString
' Stop the service
controller.Stop()
' Start the service
controller.Start()
C#
controller.MachineName = ".";
controller.ServiceName = "IISADMIN";
string status = controller.Status.ToString();
// Stop the service
controller.Stop();
// Start the service
controller.Start();
When I try happen this error:
System.InvalidOperationException = {"Cannot stop wuauserv service on computer '.'."}
InnerException = {"The service has not been started"}
System.ComponentModel.Win32Exception = {"The service has not been started"}
ErrorCode = -2147467259
NativeErrorCode = 1062
How to correct? ThX!