我有一个Web应用程序c#托管在装有Windows Server 2008的计算机上的IIS上,我通过C#在Windows Server cmd上运行了一个命令,但是它不起作用,我在计算机上本地尝试了该命令,并且该命令可以正常工作,我不知道为什么它不能在装有Windows服务器的计算机上运行,我使用了此源代码,我放了一个日志但没有抛出任何错误。
protected void btnReboot_Click(object sender, EventArgs e)
{
try
{
//StartShutDown("-l");
StartShutDown("-f -r -t 5");
Log2("MNS OK");
}
catch (Exception ex)
{
Log2("MNS ERROR " + ex.ToString());
}
}
private static void StartShutDown(string param)
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = "cmd";
proc.WindowStyle = ProcessWindowStyle.Hidden;
proc.Arguments = "/C shutdown " + param;
Process.Start(proc);
}
您实际上可以捕获由redirecting the standard error启动的进程的错误输出。一个例子是这样的:
private static void StartShutDown(string param)
{
Process p = new Process();
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true; // You need to set this
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C shutdown " + param;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
string stdoutx = p.StandardOutput.ReadToEnd();
string stderrx = p.StandardError.ReadToEnd(); // here is where you get the error output string
p.WaitForExit();
Console.WriteLine("Exit code : {0}", p.ExitCode);
Console.WriteLine("Stdout : {0}", stdoutx);
Console.WriteLine("Stderr : {0}", stderrx);
}
一旦拥有Stderr,您就可以检查其内容,如果它不为空,那么您会知道发生了错误。