2013-02-22 82 views
2

我試圖獲取輸出以顯示我的機器上當前打開的文檔,但無論如何它都會返回NULL。從Process StandardOutput獲取值

StringCollection values = new StringCollection(); 
var proc = new Process 
{ 
    StartInfo = new ProcessStartInfo 
    { 
      FileName = "openfiles.exe", 
      Arguments = "/query /FO CSV /v", 
      UseShellExecute = false, 
      RedirectStandardOutput = true, 
      CreateNoWindow = true 
    } 
}; 
proc.Start(); 
while (!proc.StandardOutput.EndOfStream) 
{ 
    string line = proc.StandardOutput.ReadLine(); 
    values.Add(line); 
} 
foreach (string sline in values) 
MessageBox.Show(sline); 

編輯:

在進一步審查我看到,我得到一個異常的問題。在我的診斷來看,我得到如下: Proc.BasePriority THRE類型System.InvalidOperationException的異常

編輯:

想抽出代碼:

string val = proc.StandardOutput.ReadToEnd(); 
MessageBox.Show(val); 

另外一個NULL值在返回時,即使在proc.start();之後,Proc仍然有錯誤。

+0

您確定該流程實際啓動並運行嗎?也許可以嘗試compile.StandardOutput.ReadToEnd()而不是循環直到EndOfStream。 – 2013-02-22 20:36:31

+0

這也返回一個NULL值。 string val = proc.StandardOutput.ReadToEnd(); MessageBox.Show(val); – Saren 2013-02-22 20:45:07

回答

9

您必須同時讀取標準輸出和標準錯誤流。這是因爲你不能從同一個線程讀取它們。

要達到此目的,您必須使用eventhandlers,這將在單獨的線程上調用。

將代碼編譯爲anycpu,因爲openfiles具有32位和64位的變體。如果架構不匹配,它可能找不到可執行文件。

從錯誤流中讀取的行被前置! >所以他們在輸出中脫穎而出。

StringCollection values = new StringCollection(); 
    var proc = new Process 
    { 
     StartInfo = new ProcessStartInfo 
     { 
      FileName = "openfiles.exe", 
      Arguments = "/query /FO CSV /v", 
      UseShellExecute = false, 
      RedirectStandardOutput = true, 
      RedirectStandardError = true, 
      CreateNoWindow = false 
     } 
    }; 
    proc.Start(); 

    proc.OutputDataReceived += (s,e) => { 
     lock (values) 
     { 
      values.Add(e.Data); 
     } 
    }; 
    proc.ErrorDataReceived += (s,e) => { 
     lock (values) 
     { 
      values.Add("! > " + e.Data); 
     } 
    }; 

    proc.BeginErrorReadLine(); 
    proc.BeginOutputReadLine(); 

    proc.WaitForExit(); 
    foreach (string sline in values) 
     MessageBox.Show(sline);