使用Web应用程序在Windows Server上执行cmd命令

我有一个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);
        }

wangdaren1 回答:使用Web应用程序在Windows Server上执行cmd命令

实际上,您可以捕获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后,您可以检查其内容,如果它不为空,则说明发生了错误。

本文链接:https://www.f2er.com/2774803.html

大家都在问