3

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?

helb
  • 7,609
  • 8
  • 36
  • 58
Jerry
  • 67
  • 1
  • 7

2 Answers2

9

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.

helb
  • 7,609
  • 8
  • 36
  • 58
  • I used `ServiceController x = new ServiceController("ASP.NET State Service");` which worked fine on my PC - so it doesnt suggest thats it – BugFinder Aug 07 '15 at 09:00
  • @BugFinder Yes, since the documentation *for the constructor* says that "This can also be the display name for the service." However, for the ServiceName property that is **not** the case. – helb Aug 07 '15 at 09:02
  • Ah, I missed that. But its worth noting the OP has the choice of doing that. – BugFinder Aug 07 '15 at 09:03
  • @BugFinder I added that to my answer. I like to use the service name rather than the display name since they are generally shorter and simpler. – helb Aug 07 '15 at 09:07
  • Oh, dont disagree, but not everyone seems to know how to get the short name - although its not hard. – BugFinder Aug 07 '15 at 09:08
  • Done. Add also gave a +1 for the edited part which i really had to use. – Jerry Aug 07 '15 at 09:15
2

Open Visual studio as Administrator

Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45
josue
  • 21
  • 1