2013-04-10 86 views
2

我發現了這樣的代碼。它運行一個進程,然後打印它寫入標準輸出的內容。問題是,它不打印任何東西,直到過程退出,這可能需要很長時間(或根本不需要)。因此,我寧願打印輸出AS IT GOES。我怎樣才能做到這一點?打印輸出,因爲它與進程

var startInfo = new ProcessStartInfo("cmd", "/c sleepy.bat") 
    {RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; 
var p = new Process(){StartInfo = startInfo}; 
p.Start(); 
string output = p.StandardOutput.ReadToEnd(); 
Console.WriteLine(output); 

sleepy.bat可能是

echo "About to execute really slow query.." 
sleep 20 
echo "Finished!" 

回答

2

嘗試使用p.StandardOutput.BeginOutputReadLine()。您將收到來自OutputDataReceived事件中的過程的輸出。

有關擴展示例,請參閱MSDN article

+0

感謝亞歷克斯,這工作。 – 2013-04-10 16:27:35