简体   繁体   English

从 C# 代码停止 Windows 服务不起作用

[英]Stopping Windows Service from C# code doesn't work

My code has to stop a service.我的代码必须停止服务。 I'm using the code below:我正在使用下面的代码:

ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.UseShellExecute = true;
processInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + @"\System32\cmd.exe";
processInfo.Arguments = "sc stop SERVICENAME";
processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
processInfo.Verb = "runas"; //The process should start with elevated permissions

Process process = new Process() { EnableRaisingEvents = true, StartInfo = processInfo };
process.Start();
process.WaitForExit();

I then check the service state from a CMD window (manually, not in my program) with the following command: sc SERVICENAME query .然后,我使用以下命令从CMD窗口(手动,而不是在我的程序中)检查服务状态: sc SERVICENAME query But the state is still RUNNING .但是状态仍然是RUNNING

When I stop it opening cmd as Administrator and executing the same commands ( sc stop SERVICENAME ), it just works.当我停止它以管理员身份打开cmd并执行相同的命令( sc stop SERVICENAME )时,它就可以工作。

Any thoughts about why it doesn't work from my code?关于为什么我的代码不起作用的任何想法?

With C# and .NET, it is better if you use the ServiceController class like this:对于 C# 和 .NET,最好像这样使用ServiceController类:

ServiceController controller = new ServiceController("SERVICENAME");

controller.Stop();

Executing cmd.exe with sc stop SERVICENAME as arguments won't do anything.使用sc stop SERVICENAME作为参数执行cmd.exe不会做任何事情。 It will only start the command prompt.它只会启动命令提示符。

To fix your problem, simply execute sc.exe directly, passing stop SERVICENAME as the arguments.要解决您的问题,只需直接执行sc.exe ,将stop SERVICENAME作为参数传递。

// ...
processInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "sc.exe");
processInfo.Arguments = "stop SERVICENAME";
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM