Leonardo
Leonardo

Reputation: 1363

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?

Upvotes: 1

Views: 1471

Answers (2)

Yacoub Massad
Yacoub Massad

Reputation: 27861

With C# and .NET, it is better if you use the ServiceController class like this:

ServiceController controller = new ServiceController("SERVICENAME");

controller.Stop();

Upvotes: 3

sstan
sstan

Reputation: 36473

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";
// ...

Upvotes: 2

Related Questions