Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing contents of standard output in C#

Tags:

c#

.net

I am using external library ( .dll ), some of it's methods (including constructors) write stuff to standard output (a.k.a console) because it was intended to be used with console apps. However I am trying to incorporate it into my windows forms applications, so I would like to capture this output and display it in a way I like. I.e. "status" text field within my window.

All I was able to find was ProcessStartInfo.RedirectStandardOutput, though apparently it doesn't fit my needs, because it is used with an additional application (.exe) in examples. I am not executing external apps, I am just using a dll library.

like image 576
Sejanus Avatar asked Oct 25 '11 04:10

Sejanus


2 Answers

Create a StringWriter, and set the standard output to it.

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

Now, anything printed to console will be inserted into the StringWriter, and you can get its contents anytime by calling stringw.ToString() so then you could do something like textBox1.AppendText(stringw.ToString()); (since you said you had a winform and had a status text field) to set the contents of your textbox.

like image 82
Zhanger Avatar answered Sep 19 '22 18:09

Zhanger


Would using the Console.SetOut method get you close enough to what you are after?

It would provide you the ability to get the text written to the console into a stream that you could write out somewhere anyway.

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

Excerpt from above link:

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();
like image 44
Glenn Avatar answered Sep 18 '22 18:09

Glenn