2010-06-04 45 views
0

我需要在類中運行Dos命令。我的問題是重定向選項似乎阻止了命令的運行。
這裏是我的代碼:在c#中的Dos命令 - RedirectStandardError /輸出問題

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; 
    } 

任何想法,爲什麼?

感謝

託尼

+0

你會得到什麼輸出? – SLaks 2010-06-04 14:22:37

回答

3

這是XCOPY.EXE的怪癖,你必須標準輸入重定向爲好。檢查this thread爲我的原始診斷。不需要使用cmd.exe btw,只需直接調用xcopy。

+0

就是這樣!謝謝。上面的代碼以及我的代碼現在都可以工作。我確實注意到其他命令被正確執行。只是xcopy不起作用。 謝謝 託尼 – tony 2010-06-04 15:23:46