2011-06-02 16 views
3

的代碼如下:無法從cmd.exe的執行得到輸出

ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c" + command); 
startInfo.CreateNoWindow = true; 
startInfo.UseShellExecute = false; 
startInfo.WindowStyle = ProcessWindowStyle.Normal; 
startInfo.Arguments = arguments; 
startInfo.RedirectStandardError = true; 
startInfo.RedirectStandardOutput = true; 

Process process = Process.start(startInfo); 
StreamReader srOutput = process.StandardOutput; 
string output = srOutput.ReadToEnd(); 

的命令是rmdir /s /q 123

我期望能獲得「系統找不到指定文件」變量output COS內「123」是不存在的文件路徑。但output是一個空字符串。爲什麼以及如何得到輸出?

+0

仍然有疑問,請參閱下面的註釋... – yeeen 2011-06-02 07:17:42

回答

5

您期待看到的消息將在StandardError上,而不是StandardOutput

+0

爲什麼它有時會在預期的錯誤消息中輸出而不是?例如,MOVE命令,如果我沒有打開和關閉目標路徑的引號。 「語法如果命令不正確」msg是在'StandardOutput'而不是'StandardError'並且'StandardError'是空的。 – yeeen 2011-06-02 06:46:30

+0

您正在使用命令行處理器。讓用戶誤輸入命令可能太常見了,不能稱之爲錯誤。只是不要使用cmd.exe來執行此操作,而應使用System.IO命名空間中的類。 – 2011-06-02 12:36:21

+0

@yeeen - 微軟在編寫執行命令的代碼時只是不一致。 – 2011-06-02 23:00:22