Failed to start and stop service using ServiceController
I have the following methods to start and stop a service. I am calling this method from another console application for debugging as I was using methods in a class library (DLL).
The application runs with administrator rights.
public void ServiceStart()
{
ServiceController service = new ServiceController();
service.ServiceName = "ASP.NET State Service";
service.Start();
}
public void ServiceStop()
{
ServiceController service = new ServiceController();
service.ServiceName = "ASP.NET State Service";
service.Stop();
}
But when I call Start()
or Stop()
, an exception is thrown with the following message:
Unable to open the ASP.NET State Service service on the computer. '
Can anyone help me?
source to share
You need to pass the Service Name , not the Display Name . Always check the properties of the service in the Services application.
Please try again with
service.ServiceName = "aspnet_state";
Alternatively, you can instantiate the ServiceController using the display name:
ServiceController service = new ServiceController("ASP.NET State Service");
as the documentation for the constructor argument says:
The name that identifies the service to the system. It can also be the display name for the service.
Also note that the call
service.Start();
returns immediately without waiting for the service to start. You should call
service.WaitForStatus(ServiceControllerStatus.Running);
if you want to make sure the service is started before your application continues.
source to share