2011-12-25 49 views
0

運行此代碼:閱讀從工藝標準輸出,總是空

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.FileName = "tool.exe"; 
p.Start(); 
p.WaitForExit(); 

使tool.exe運行,並輸出到標準輸出一些內容。但是,如果我嘗試捕捉使用內容:

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.CreateNoWindow = true; 
p.StartInfo.FileName = "tool.exe"; 
p.Start(); 
string output = p.StandardOutput.ReadToEnd(); 
p.WaitForExit(); 

Console.WriteLine(output); 
Console.ReadLine(); 

然後沒有獲取輸出,即我的變量「輸出」始終是空的。

我已經驗證了tool.exe確實輸出到標準輸出(而不是標準錯誤)。

任何人都知道發生了什麼?開始在這裏覺得愚蠢,因爲它似乎是一個真正的教科書範例......

+0

它可能等待輸入。 – SLaks 2011-12-25 21:25:33

+0

感謝您的建議,但如果tool.exe運行時沒有參數,它會立即輸出一些內容(即時消息試圖捕獲)。 – Marcus 2011-12-25 21:28:50

回答

0
p.OutputDataReceived += new DataReceivedEventHandler 
     (
      delegate(object sender, DataReceivedEventArgs e) 
      {     
       using (StreamReader output = p.StandardOutput) 
       { 
        retMessage = output.ReadToEnd(); 
       } 
      } 
     ); 

試試這個:)

+0

謝謝!儘管如此,仍然沒有運氣..沒有任何東西可以通過。 – Marcus 2011-12-25 22:01:28

+0

是tool.exe控制檯應用程序?你有沒有嘗試在cmd.exe中運行它?什麼是輸出? – Elastep 2011-12-25 22:03:56

+0

是的,這是一個控制檯應用程序(我包括在我的項目中)。它會打印幾個字符串。 – Marcus 2011-12-25 22:06:27