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();
Clyde
  • 311
  • 2
  • 14
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/206915/discussion-on-question-by-clyde-servicecontroller-cant-stop-the-service-c). – Samuel Liew Jan 30 '20 at 12:09
  • @samuel. Yes i tried, unfortunately clyde had low rep for me to initiate chat, may I know how its possibleb? – Clint Jan 30 '20 at 18:20
  • hi Clyde, just following up,can you confirm if the below answer helped you with your query, if yes, please accept it by clicking the green tickbox, thank you – Clint Feb 10 '20 at 08:32

1 Answers1

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
Clint
  • 6,011
  • 1
  • 21
  • 28