2014-03-13 54 views
1

輸出我跑這個無法從CMD

 string path = string.Format(@"\\{0}\c$\Windows\CCM\Logs", computerName); 

     Process process = Process.Start(new ProcessStartInfo() 
     { 
      FileName = "cmd.exe", 
      Arguments = string.Format(@"net use {0} && dir {0}", path), 
      UseShellExecute = false, 
      RedirectStandardOutput = true, 
      RedirectStandardError = true, 
      CreateNoWindow = true 
     }); 

     string result = process.StandardOutput.ReadToEnd() + " " + process.StandardError.ReadToEnd(); 
     process.WaitForExit(); 

     Console.WriteLine(result); 

但沒有什麼是永遠寫入控制檯。我究竟做錯了什麼?我已經瀏覽過其他所有關於此的SO線程,並做了大量的谷歌搜索,但我無法實現它的工作。

+0

'cmd.exe'在處理完命令後沒有自動關閉,它等待進一步的輸入,所以你的程序停在'process.WaitForExit'而不是'Console.WriteLine(result)'。基於事件監聽或異步輸出的建議解決方案應該可行。 – Fedor

回答

2

RedirectStandardOutput = true;RedirectStandardError = true;將重定向各自的流。爲了捕捉這些流,你需要處理OutputDataReceived事件如下:使用下面的代碼打印出來的方法,調試/控制檯

using (StreamReader reader = process.StandardError) { 
    string result = reader.ReadToEnd(); 
    System.Diagnostics.Debug.Write(result); 
} 

using (StreamReader reader = process.StandardOutput) { 
    string result = reader.ReadToEnd(); 
    System.Diagnostics.Debug.Write(result); 
} 

process.WaitForExit(); 

的standardError和StandardOutput

process.EnableRaisingEvents = true; 
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived); 
process.BeginOutputReadLine(); 
+0

這對我有用。謝謝! – user1021726

1

I'm此外,我對StartInfo的

設置以下屬性
StartInfo.UseShellExecute = false; 
StartInfo.ErrorDialog = false; 
StartInfo.RedirectStandardOutput = true; 
StartInfo.RedirectStandardError = true; 
+0

這不適合我。抱歉。 – user1021726

+0

如果再看一下上面的代碼,我已經在'StartInfo'(ErrorDialog除外)中設置了所有這些屬性。感謝您的編輯! :) – user1021726

+0

@ user1021726該代碼是我如何在我的應用程序中設置它,打印出來自ffmpeg的輸出,它適用於我。當它爲你工作時,使用接受答案中的代碼。 :) – Jehof

3

您需要使用/C選項cmd.exe否則孩子過程中不會出口。

/C執行字符串指定的命令,然後終止

(類型cmd /?在命令提示符下以獲取更多信息)

+0

點2是不正確的。來自MSDN'不要等到子進程退出,然後才能讀取其重定向錯誤流的結尾。 p.WaitForExit();先閱讀錯誤流,然後等待。# – Jehof

+0

@Jehof:你說得對。對不起。我會更新我的帖子。 –

+0

雖然你的(現在刪除的)其他點是錯誤的,但使用'/ c'標誌確實有幫助。謝謝。 – user1021726

1

我想你面臨一個僵局中描述documentation

死鎖條件結果如果父進程調用p.StandardOutput.ReadToEnd後跟p.StandardE rror.ReadToEnd和子進程寫入足夠的文本來填充它的錯誤流。父進程將無限期地等待子進程關閉其StandardOutput流。子進程將無限期地等待父進程從完整的StandardError流中讀取。

爲了避免這種情況,你應該有一個流使用異步讀取操作:

p.BeginOutputReadLine(); 
string error = p.StandardError.ReadToEnd(); 
p.WaitForExit(); 

禮貌應該去MSDN documentation

+0

也許吧。我已經接受了一個也在進程中的答案。BeginOutputReadLine()'我認爲對解決方案有貢獻。我不知道進程僵局,儘管如此感謝! – user1021726