2012-11-06 50 views
0

當我的應用程序試圖在控制檯上寫入內容時,我需要捕獲該事件。如何在事件或方法中將文本發送到控制檯輸出

Console.WriteLine("Any text"); 

是否可以將文本發送到事件或方法的控制檯輸出?

+0

您可以[重定向'Console.Out'(http://stackoverflow.com/questions/6024172/is-it-possible-to-intercept -console-output) – PHeiberg

+0

在這裏,試試這個,有些類似於你的要求。 http://stackoverflow.com/questions/11911660/redirect-console-writeline-from-windows-application-to-a-string –

回答

1

一種方法是創建一個新的流控,如本文所示:

http://mel-green.com/2010/01/progressstream/

然後,你需要設置這是該數據流控制檯寫入,例如

MemoryStream ms = new MemoryStream(); 
ProgressStream progressStream = new ProgressStream(ms); 
Console.SetOut(new StreamWriter(progressStream)); 

然後使用進度流的事件來查看它的寫入時間。

+0

其實有第三方引用。他們只是使用Console.WriteLine。我已經包含這些DLL。所以我不能應用這個解決方案,因爲我不能修改它們。 –

+0

第三方參考?我什麼也沒有看到,所有的來源都在那裏。我不確定你的意思。 –

+0

讓我試試解決方案。我認爲它應該適合我。 –

0

這可能對你有幫助:

using System; 
using System.IO; 

namespace nsStreams 
{ 
    public class Redirect 
    { 
     static public void Main() 
     { 
      FileStream ostrm; 
      StreamWriter writer; 
      TextWriter oldOut = Console.Out; 
      try 
      { 
       ostrm = new FileStream ("./Target.txt", FileMode.OpenOrCreate, FileAccess.Write); 
       writer = new StreamWriter (ostrm); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine (e.Message); 
       return; 
      } 
      Console.SetOut (writer); 

      Console.SetOut (oldOut); 
      writer.Close(); 
      ostrm.Close(); 
      Console.WriteLine ("Done"); 
     } 
    } 
} 
相關問題