ServiceController - 无法停止服务 [C#]

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

我在这里阅读了很多有类似问题的帖子,但是 none 帮助我解决了我的问题。 我想用 ServiceController 对象停止服务。但它失败了,我得到一个异常:System.ComponentModel.Win32Exception (0x80004005)。我不明白为什么..我 运行 程序 "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);
   }
}

如果我从代码中调用 net stop 命令,那么一切正常。为什么?

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

在我们继续聊天讨论后 ServiceController 发现以下内容:

  • ServiceController 能够 Start 服务,但不能 Stop
  • 从系统日志中可以明显看出,ServiceController 在尝试停止时崩溃了
  • ServiceControllers Start & Stop 可以与其他服务一起正常工作,例如 PrintSpooler
  • 使用CMDProcess.Start我们可以通过sc stop "servicename"
  • 停止服务
  • 最后问题出在服务本身及其构建方式上