在C#中捕获标准输出的内容

时间:2011-10-25 04:14:19

标签: c# .net

我正在使用外部库(.dll),其中一些方法(包括构造函数)将内容写入标准输出(a.k.a控制台),因为它旨在与控制台应用程序一起使用。但是我试图将它合并到我的Windows窗体应用程序中,所以我想捕获此输出并以我喜欢的方式显示它。即我的窗口中的“状态”文本字段。

我能找到的只是ProcessStartInfo.RedirectStandardOutput,虽然它显然不符合我的需要,因为它在示例中与其他应用程序(.exe)一起使用。我没有执行外部应用程序,我只是使用dll库。

2 个答案:

答案 0 :(得分:7)

创建StringWriter,并将标准输出设置为它。

StringWriter stringw = new StringWriter();
Console.SetOut(stringw);

现在,打印到控制台的任何内容都会插入到StringWriter中,您可以随时通过调用stringw.ToString()来获取其内容,这样您就可以执行textBox1.AppendText(stringw.ToString());之类的操作(因为您说过您有一个winform并有一个状态文本字段)来设置文本框的内容。

答案 1 :(得分:2)

使用Console.SetOut方法会让你足够接近你所追求的目标吗?

它将使您能够将写入控制台的文本转换为您可以在某处写出的流。

http://msdn.microsoft.com/en-us/library/system.console.setout.aspx

以上链接摘录:

Console.WriteLine("Hello World");
FileStream fs = new FileStream("Test.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
Console.SetOut(tmp);
Console.WriteLine("Hello World");
sw.Close();