[使用Web应用C#在Windows Server 2008上执行cmd命令

问题描述 投票:0回答:1

我有一个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);
        }
c# .net visual-studio iis-7
1个回答
0
投票

您实际上可以通过重定向标准错误来捕获启动过程中的错误输出。一个例子是这样的:

private static void StartShutDown(string param)
{
    Process p = new Process();
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;         
    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();             
    p.WaitForExit();

    Console.WriteLine("Exit code : {0}", p.ExitCode);
    Console.WriteLine("Stdout : {0}", stdoutx);
    Console.WriteLine("Stderr : {0}", stderrx);
}

一旦拥有Stderr,您就可以检查其内容,如果它不为空,那么您会知道发生了错误。

© www.soinside.com 2019 - 2024. All rights reserved.