I have the below methods to start and stop a service. I call this method from another Console application to debug since I've used the methods in a Class Library(DLL).
The application is started with administrative 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 with the following message is thrown:
Cannot open ASP.NET State Service service on computer '.'
Can someone help me out?
You have to pass the Service name, not the Display name. Always check the service properties in the "Services" application.
Try again with
service.ServiceName = "aspnet_state";
Alternatively, you can create the ServiceController instance using the display name:
ServiceController service = new ServiceController("ASP.NET State Service");
since the documentation for the constructor argument says:
The name that identifies the service to the system. This can also be the display name for the service.
Also note that a call to
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 running before your application continues.