我需要在類中運行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;
}
任何想法,爲什麼?
感謝
託尼
你會得到什麼輸出? – SLaks 2010-06-04 14:22:37