2010-08-31 28 views
0

這是windows-application-form的代碼;我想要執行的批處理文件顯示我通過RedirectStandardOutput = false;得到的shell屏幕上的輸出,但我也希望輸出被同時重定向到日誌文件。爲此,我使用RedirectStandardOutput = true;如何重定向輸出以及同時獲得shell屏幕上的輸出

當然,一次只能使用一個!

System.Diagnostics.Process p = new System.Diagnostics.Process(); 
p.StartInfo.FileName = "c:\test\build.bat"; 

p.StartInfo.UseShellExecute = false; 

p.StartInfo.RedirectStandardOutput = true; // if I use false all the commented lines below are not applicable for comments 

p.Start(); 

string output = null; 
//try 
//{ 

output = p.StandardOutput.ReadToEnd(); 

//} 
//catch (Exception ex) 
//{ 
// MessageBox.Show(ex.ToString()); 
//} 

System.IO.File.WriteAllText("c:\test\log.txt", output); 

回答

0

捕獲輸出並自己將其打印到屏幕上。這就是tee命令在大多數非Windows操作系統上滿足這種需求的方式。在你的代碼的某個地方

System.Diagnostics.Process p = new System.Diagnostics.Process(); 
p.StartInfo.FileName = "c:\test\build.bat"; 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler); 
p.Start(); 

而且有一個事件處理程序:

+0

這不是很有幫助,他/她顯然是在使用Windows,因爲他們正在寫C:\ – codemonkeh 2010-08-31 04:47:42

+0

@codemonkeh:你認爲我的第一句話本身更有用嗎?我完全知道我們在這裏與Windows打交道,這就是爲什麼我沒有說「只使用'tee'」,但是該怎麼做。事實上,在面向命令行的系統上執行POSIX標準化命令是一種常見的事情,這只是背景信息,有助於說服OP確信這是正確的方法。 – 2010-08-31 05:00:48

+0

我認爲@ system-rule正在尋找一種特定的代碼內解決方案,所以他們更喜歡一個例子。對不起,如果我冒犯了你。 – codemonkeh 2010-08-31 05:22:24

0

你可以嘗試這樣的事情從MSDN: Process.BeginOutputReadLine Method採取

private static void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{ 
    if (!String.IsNullOrEmpty(outLine.Data)) 
    { 
     Console.WriteLine(outLine.Data); 
     System.IO.File.AppendAllText("c:\test\log.txt", outLine.Data); 
    } 
} 

例。將文件保持爲可寫狀態或甚至緩衝文件會更有效率,但這會使範例縮短。

+0

感謝您的良好響應我試過這個,但它dosent調用SortOutputHandler和創建文件(日誌文件),但它給出了shell屏幕上的輸出,當我改變這個p.StartInfo.RedirectStandardOutput = false; (true - > false) 我的問題仍然沒有解決:( 我想要的東西,讓我在屏幕上輸出以及我可以得到一個文件的輸出,以便我可以維護一個日誌文件... – user434934 2010-08-31 08:23:28