Capturing the contents of standard output in C #

I use an external library (.dll), some of its methods (including constructors) write material to standard output (aka console), because it was intended for use with console applications. However, I am trying to incorporate it into my applications for Windows forms, so I would like to capture this output and display it the way I like. That is, the "status" text box in my window.

All I managed to find was ProcessStartInfo.RedirectStandardOutput, although it does not seem to meet my needs, because it is used with an additional application (.exe) in the examples. I do not run external applications, I just use the dll library.

+6
source share
2 answers

Create a StringWriter and set the standard output for it.

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

Now everything that is printed on the console will be inserted into StringWriter, and you can get its contents at any time by calling stringw.ToString() so that later you can do something like textBox1.AppendText(stringw.ToString()); (since you said that you have winform and you have the status of a text field) to set the contents of your text field.

+7
source

Will using the Console.SetOut method bring you closer to what you are after?

It will give you the opportunity to get the text recorded on the console into a stream that you can still write somewhere.

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

Excerpt from the link above:

 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(); 
+2
source

Source: https://habr.com/ru/post/900009/


All Articles