2012-06-14 34 views
0

我想打電話給使用的Process.Start命令提示符下命令,然後使用StandardOutput我想在我的應用程序中使用的StreamReader讀取,但是當我運行下面的程序,在MessageBox我只是尋找路徑,直到調試,我在參數中陳述的命令不會附帶說明。傳遞參數給的ProcessStartInfo類

ProcessStartInfo info = new ProcessStartInfo("cmd.exe", "net view"); 
      info.UseShellExecute = false; 
      info.CreateNoWindow = true; 
      info.RedirectStandardOutput = true;  

      Process proc = new Process(); 
      proc.StartInfo = info; 
      proc.Start(); 

      using(StreamReader reader = proc.StandardOutput) 
      { 
       MessageBox.Show(reader.ReadToEnd()); 
      } 

這裏my net view命令從不執行。

回答

4

如果你想與cmd運行命令,你必須得指定/c參數:

new ProcessStartInfo("cmd.exe", "/c net view"); 

在這種情況下,然而,你不需要cmd的。 net是土生土長的程序,並且可以作爲被執行,無殼:

new ProcessStartInfo("net", "view"); 
+0

感謝@Joey:幫助很大 – Abbas

+1

如果它回答了你的問題,爲什麼不點擊複選標記? – Almo

1

還要記住攔截StandardErrorOutput還是會看到什麼:

var startInfo = new ProcessStartInfo("net", "view"); 
startInfo.UseShellExecute = false; 
startInfo.CreateNoWindow = true; 
startInfo.RedirectStandardError = true; 
startInfo.RedirectStandardOutput = true; 

using (var process = Process.Start(startInfo)) 
{ 
    string message; 

    using (var reader = process.StandardOutput) 
    { 
     message = reader.ReadToEnd(); 
    } 

    if (!string.IsNullOrEmpty(message)) 
    { 
     MessageBox.Show(message); 
    } 
    else 
    { 
     using (var reader = process.StandardError) 
     { 
      MessageBox.Show(reader.ReadToEnd()); 
     } 
    } 
}