Get an event hook to Console.WriteLine
Asked Answered
W

1

5

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?

Wil answered 24/2, 2014 at 12:38 Comment(2)
Have you tried redirecting the Console standard output to your own stream?Aglitter
Try monkey patching Console.WriteLine, eg. #9685304 I've never tried this myself.Hutchens
T
11

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

Tarra answered 24/2, 2014 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.