1

currently trying to write a C# program which can detect a specific status of a service. If the service is running, the program will close it. If the service is stopped, the program will run it.

Below is my code:

        ServiceController sc = new ServiceController("RtkAudioService");

        Console.WriteLine("Status = " + sc.Status);
        Console.WriteLine("Can Pause and Continue = " + sc.CanPauseAndContinue);
        Console.WriteLine("Can ShutDown = " + sc.CanShutdown);
        Console.WriteLine("Can Stop = " + sc.CanStop);
        Console.WriteLine("Machine Name = " + sc.MachineName);

        if (sc.Status.Equals(ServiceControllerStatus.Stopped))
        {
            sc.Start();
        } 
        else if (sc.Status.Equals(ServiceControllerStatus.Running))
        {
            sc.Stop();
        }

I have tried to stop/run various service for my pc but failed. The RtkAudioService is just one of my example that failed. All of the error message are the same:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.ServiceProcess.dll

Additional information: Cannot open RtkAudioService service on computer '.'.

Do you guys know what's happening?

Coolguy
  • 2,225
  • 12
  • 54
  • 81
  • Not sure because I don't have that service, but ServiceController constructor wants the DisplayName not the ServiceName. Probably you should pass `Realtek Audio Service` – Steve Mar 26 '15 at 15:43
  • 1
    @Steve according to msdn it can be either. I tried this and picked a random service to start/stop on my machine. I could start it fine using the name but needed to run as admin to stop it. The inner exception of the InvalidOperationException was `Access is denied` – James Mar 26 '15 at 15:45
  • Yes, checked with a ServiceName and it works. So only the permission option remains – Steve Mar 26 '15 at 15:47
  • Same problem in [this question](http://stackoverflow.com/questions/14501748/cannot-open-window-service-on-computer-in-window-application) – Claudio P Mar 26 '15 at 15:54
  • So, is it that we have to add the application manifest file and change requestedExecutionLevel level to "requireAdministrator" ? – Coolguy Mar 26 '15 at 16:18

3 Answers3

1

I had the same problem and I resolved adding this code after start or stop the service:

sc.WaitForStatus(ServiceControllerStatus."status");

0

Run VS as admin and it solved the problem in debugging.

Because program must have right to run or stop service likely Administrator right.

Danh
  • 5,916
  • 7
  • 30
  • 45
NewDeveloper
  • 85
  • 3
  • 9
0

The same case just happened to me and was solved by adding "sc.Refresh()" before checking the status (maybe the status is not up to date and therefore you are trying to start a running proccess). I would try to print the status of the service prior the if's, and ensure the results match your expectations.

Shay Yzhakov
  • 975
  • 2
  • 13
  • 31