I want to create a process which uses shutdown.exe to shut down the computer after a given time.
Here is my code:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "shutdown.exe";
startInfo.Arguments = "–s –f –t " + seconds;
Process.Start(startInfo);
Where seconds is an int local variable, the user decides.
When i run my code nothing happens. But when i manually go in cmd prompt and type:
shutdown.exe - s -f -t 999
then Windows will make a popup and tell me that the system will shutdown in 16 mins.
The reason i think it's because of the multiple arguments, is that my method to abort the ongoing system shutdown works(where i created the systemshutdown manually from cmd prompt). This is almost the same, except at startInfo.Argument:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "shutdown.exe";
startInfo.Arguments = "-a";
Process.Start(startInfo);
A quick inspection of shutdown.exe's usage message reveals that it expects option arguments following slashes ('/') not dashes ('-').
Replacing the line:
startInfo.Arguments = "–s –f –t " + seconds;
With:
startInfo.Arguments = "/s /f /t " + seconds;
Yields a working result on my box with C# express 2010.
Also, you can redirect standard error and standard out of the started process to be read by your program, such that you can tell what happened after it ran. To do this, you can store the Process object and wait for the underlying process to exit so that you can check if everything went well.
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
Process p = Process.Start(startInfo);
string outstring = p.StandardOutput.ReadToEnd();
string errstring = p.StandardError.ReadToEnd();
p.WaitForExit();
Unfortunately, I can't tell you why the command line version accepts 'dash' prefixes on the options and the C# executed version doesn't. However, hopefully what you're after is a working solution.
The full listing of code below:
int seconds = 100;
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "shutdown.exe";
startInfo.Arguments = "/s /f /t " + seconds;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
Process p = Process.Start(startInfo);
string outstring = p.StandardOutput.ReadToEnd();
string errstring = p.StandardError.ReadToEnd();
p.WaitForExit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With