Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an event hook to Console.WriteLine

In a c# console application, is there a way to get a notification whenever text is written to the console via Console.WriteLine and Console.Write?

Whenever this event fires, it should be possible to do things like change the text before it is written, redirect it to a file, or change the current Console.ForegroundColor.

I know that a simple way to accomplish this is to never call Console.WriteLine directly, but instead always call my own custom wrapper method.

Another even better approach is to write a custom ConsoleTraceListener, and output all text via trace.TraceInformation(). I have done that and it works just fine.

However this does not work if the Console.WriteLine call is inside another assembly which should remain unchanged.

So is there any way to react to Console.WriteLine calls without modifying the code that makes those calls?

like image 811
HugoRune Avatar asked Feb 24 '14 12:02

HugoRune


1 Answers

You can use Console.SetOut to set a custom Writer class. In this class you can make your own write function.

like image 104
David Avatar answered Sep 18 '22 18:09

David