我想创建一个使用 shutdown.exe 在给定时间后关闭计算机的进程。
这是我的代码:
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);
seconds 是一个 int 局部变量,由用户决定。
当我运行我的代码时,没有任何反应。但是当我手动进入 cmd 提示符并键入:
shutdown.exe - s -f -t 999
然后 Windows 会弹出一个窗口,告诉我系统将在 16 分钟后关闭。
我认为这是由于多个参数的原因,是我中止正在进行的系统关闭的方法有效(我在 cmd 提示符下手动创建了系统关闭)。这几乎是相同的,除了 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);
最佳答案
快速检查 shutdown.exe 的用法消息表明,它期望选项参数跟在斜线(“/”)之后,而不是破折号(“-”)之后。
替换行:
startInfo.Arguments = "–s –f –t " + seconds;
与:
startInfo.Arguments = "/s /f /t " + seconds;
使用 C# express 2010 在我的盒子上产生了一个工作结果。
此外,您还可以将标准错误和标准从已启动的进程重定向到您的程序以供程序读取,这样您就可以知道程序运行后发生了什么。为此,您可以存储 Process 对象并等待底层进程退出,以便您可以检查是否一切顺利。
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
Process p = Process.Start(startInfo);
string outstring = p.StandardOutput.ReadToEnd();
string errstring = p.StandardError.ReadToEnd();
p.WaitForExit();
不幸的是,我无法告诉您为什么命令行版本在选项上接受“破折号”前缀而 C# 执行版本不接受。但是,希望您所追求的是一个可行的解决方案。
完整的代码 list 如下:
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();
关于c# - 具有多个参数的 Shutdown.exe 进程,不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8915165/