Write Console window output to multiple places in C#

[example]

This example captures output sent to the Console window and displays it in multiple controls plus the Console window. It is based on an excellent reply by user Servy on Stack Overflow.

The following class is a TextWriter that represents a list if places where it should write text destined to the Console window.

// Represent a list of TextWriter objects.
public class ListTextWriter : TextWriter
{
    private List<TextWriter> Writers = new List<TextWriter>();

    // Add a new textWriter to the list.
    public void Add(TextWriter writer)
    {
        Writers.Add(writer);
    }

    public override void Write(char value)
    {
        foreach (var writer in Writers)
            writer.Write(value);
    }

    public override void Write(string value)
    {
        foreach (var writer in Writers)
            writer.Write(value);
    }

    public override void Flush()
    {
        foreach (var writer in Writers)
            writer.Flush();
    }

    public override void Close()
    {
        foreach (var writer in Writers)
            writer.Close();
    }

    public override Encoding Encoding
    {
        get { return Encoding.Unicode; }
    }
}

It’s Add method adds a TextWriter object to this object’s Writers list. The overridden Write, Flush, and Close methods simply loop through the control’s writers and calls the corresponding methods for each.

The main program uses this class in the following code.

// Install a new output TextWriter and the
// Console window's default output writer.
private void Form1_Load(object sender, EventArgs e)
{            
    ListTextWriter list_writer = new ListTextWriter();
    list_writer.Add(new TextBoxWriter(txtConsole));
    list_writer.Add(new TextBoxWriter(lblConsole));
    list_writer.Add(Console.Out);

    Console.SetOut(list_writer);
}

This code makes a new ListTextWriter. It then adds two TextBoxWriter controls (from the previous post) attached to a TextBox and a Label. It also adds the Console window’s default output TextWriter. Finally, the code calls the Console object’s SetOut method to make it use the new ListTextWriter.

Now when the program sends text to the Console window, the ListTextWriter sends the text to the TextBox, Label, and normal Console window output writer.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in Uncategorized and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.