2013-04-04 68 views
15

我執行命令提示符下命令如下:C#執行shell命令並獲得結果

string cmd = "/c dir" ; 
System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
proc.StartInfo.FileName = "cmd.exe" 
proc.StartInfo.Arguments = cmd; 
proc.StartInfo.UseShellExecute = false; 
proc.StartInfo.RedirectStandardOutput = true; 
proc.Start(); 

如何我得到命令的輸出?

+0

查看如何使用'ReadToEnd'method這樣的回答:http://stackoverflow.com/a/7160384/214222 – 2013-04-04 20:31:41

回答

19

試試這個

string output = proc.StandardOutput.ReadToEnd(); 
+2

好的,謝謝!有效! – Mika 2013-04-06 05:11:29

+0

如何設置「proc.StartInfo.UseShellExecute = true;」我如何得到相同的結果? – anion 2017-06-22 13:25:27

+0

當出現錯誤時,這不會捕獲輸出。 – Arjang 2017-06-26 23:11:52