So someone asked a question on StackOverflow today, and I gathered the best solution was to use dynamic binding.
Here follows a simple example on how to achieve it:
class DynamicConsole : TextWriter { readonly TextWriter orig; readonly TextWriter output; public DynamicConsole(string filename) { orig = Console.Out; output = File.AppendText(filename); Console.SetOut(output); } public override System.Text.Encoding Encoding { get { return output.Encoding; } } public override void Write(char value) { output.Write(value); } protected override void Dispose(bool disposing) { Console.SetOut(orig); output.Dispose(); } }
Usage:
Console.WriteLine("Real 1"); using (new DynamicConsole("Foo.txt")) { Console.WriteLine("Moo"); using (new DynamicConsole("Bar.txt")) { Console.WriteLine("Ork"); } Console.WriteLine("Bar"); } Console.WriteLine("Real 2");
When running you get the following:
This will print to the Console:
Real 1
Real 2
It will append to Foo.txt:
Moo
Bar
It will append to Bar.txt:
Ork
I will update the code later to make it generic, so any property, method or field can be used for the dynamic binding. Stay tuned!
Update:
Posted an article on CodeProject last Friday. This is a generic implementation: Dynamic binding in C#
Advertisements
Leave a Reply