ServiceController - Can't stop the service [C#]

1

I read many posts here with a similar question, but none helped me solve my problem. I want to stop the service with the ServiceController object. But it fails and I get an exception: System.ComponentModel.Win32Exception (0x80004005). I don't understand why.. I run the program with "Run as administrator".

ServiceController ctrl = ServiceController.GetServices().Where(s => s.ServiceName == "service_name").SingleOrDefault();
if (ctrl == null) return;

if (ctrl.Status.Equals(ServiceControllerStatus.Running))
{
   try 
   {
      ctrl.Stop();
   }
   catch(Exception ex)
   {
      Log(ex.ToString(), 3);
   }
}

If I call the net stop command from the code, then everything works. Why?

 Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("net stop service_name");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
c#
service
servicecontroller
asked on Stack Overflow Jan 30, 2020 by Clyde

1 Answer

1

After our continued chat discussion ServiceController following was discovered :

  • ServiceController was able to Start the service, but not Stop
  • From the System Logs it was evident that ServiceController crashes when trying to stop
  • ServiceControllers Start & Stop works fine with other services such as PrintSpooler
  • Using CMD or Process.Start we can stop service by sc stop "servicename"
  • Finally the problem was with the Service itself and the way it was constructed
answered on Stack Overflow Feb 3, 2020 by Clint

User contributions licensed under CC BY-SA 3.0