Get event binding to Console.WriteLine

In a C # console application, is there a way to get notified when text is written to the console through Console.WriteLineand Console.Write?

Whenever this event fires, it should be possible to do things such as changing the text before writing it, redirecting it to a file, or changing the current Console.ForegroundColor.

I know that the easiest way to do this is to never call Console.WriteLinedirectly, but instead always call your own custom wrapper method.

Another best approach is to write custom ConsoleTraceListenerand output all text through trace.TraceInformation(). I did this and it works fine.

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

So, is there a way to respond to calls Console.WriteLinewithout changing the code that calls these calls?

+3
source share
1 answer

You can use Console.SetOut to set a custom Writer class. In this class, you can create your own recording function.

+8
source

All Articles