2013-08-31 33 views
0

我想從Process.StandardOutput獲取數據......但我遇到了一個問題:我在進程結束時得到數據,但在執行期間沒有(不會執行)。它看起來像數據緩衝在某個地方。 當我在執行過程中手動運行進程消息apper。怎麼修?從Process.StandardOutput實時獲取數據

回答

0

這是我用來從流程中抓取輸出的東西。這是添加到一個stringbuilder,但你可以做其他事情。

private void RunWithOutput(string exe, string parameters, out string result, out int exitCode) 
    { 
     ProcessStartInfo startInfo = new ProcessStartInfo(exe, parameters); 
     startInfo.CreateNoWindow = true; 
     startInfo.UseShellExecute = false; 
     startInfo.RedirectStandardError = true; 
     startInfo.RedirectStandardOutput = true; 
     Process p = new Process(); 
     p.StartInfo = startInfo; 

     p.Start(); 

     StringBuilder sb = new StringBuilder(); 
     object locker = new object(); 
     p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args) 
     { 
      lock(locker) 
      { 
       sb.Append(args.Data); 
      } 
     }); 
     p.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args) 
     { 
      lock (locker) 
      { 
       sb.Append(args.Data); 
      } 
     }); 

     p.BeginErrorReadLine(); 
     p.BeginOutputReadLine(); 

     p.WaitForExit(); 
     result = sb.ToString(); 
     exitCode = p.ExitCode; 
    } 
+0

同樣的狗屎。線只在處理完成時才能獲得。 – KOLANICH

+0

也許是因爲不同的EOL風格? – KOLANICH

+0

否,streamreader支持3種最常用的EOL樣式。問題出在另一個地方 – KOLANICH