簡體   English   中英

C#中的DOS命令-RedirectStandardError /輸出問題

[英]Dos command in c# - RedirectStandardError/Output problem

我需要在一個類中運行Dos命令。 我的問題是重定向選項似乎阻止了命令的運行。
這是我的代碼:

public static int executeCommand(string cmd)
    {
        System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo("CMD.exe", "/C " + cmd);
        int exitCode = 0;
        //processStartInfo.RedirectStandardError = true;
        //processStartInfo.RedirectStandardOutput = true;
        processStartInfo.CreateNoWindow = true;
        processStartInfo.UseShellExecute = false;
        System.Diagnostics.Process process =
        System.Diagnostics.Process.Start(processStartInfo);

        process.WaitForExit(); //wait for 20 sec
        exitCode = process.ExitCode;
        //string stdout = process.StandardOutput.ReadToEnd();
        //string stderr = process.StandardError.ReadToEnd();
        process.Close();
        return exitCode;
    }

當我致電xcopy時:

if (executeCommand("xcopy.exe " + "/E /I /R /Y /Q c:\\temp\\*.* e:\\temp\\b1\\ ") != 0)
                Log.Error("Error detected running xcopy ");

該方法正確運行xcopy。 如果我想重定向SDTOUT和STDERR,該方法也返回0,但xcopy並未真正運行。

換句話說,這不起作用:

public static int executeCommand(string cmd)
    {
        System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo("CMD.exe", "/C " + cmd);
        int exitCode = 0;
        processStartInfo.RedirectStandardError = true;
        processStartInfo.RedirectStandardOutput = true;
        processStartInfo.CreateNoWindow = true;
        processStartInfo.UseShellExecute = false;
        System.Diagnostics.Process process =
        System.Diagnostics.Process.Start(processStartInfo);

        process.WaitForExit(); //wait for 20 sec
        exitCode = process.ExitCode;
        string stdout = process.StandardOutput.ReadToEnd();
        string stderr = process.StandardError.ReadToEnd();
        process.Close();
        return exitCode;
    }

知道為什么嗎?

謝謝

托尼

這是xcopy.exe的怪癖,您還必須重定向標准輸入。 檢查此線程以獲取原始診斷。 無需使用cmd.exe btw,只需直接調用xcopy。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM