Search code examples
c#serviceservicecontroller

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


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();

Solution

  • 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