简体   繁体   中英

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 . But the state is still RUNNING .

When I stop it opening cmd as Administrator and executing the same commands ( sc stop SERVICENAME ), it just works.

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:

ServiceController controller = new ServiceController("SERVICENAME");

controller.Stop();

Executing cmd.exe with sc stop SERVICENAME as arguments won't do anything. It will only start the command prompt.

To fix your problem, simply execute sc.exe directly, passing stop SERVICENAME as the arguments.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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