简体   繁体   中英

Unable to start and stop service using ServiceController

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.

以管理员身份打开Visual Studio

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM