Redirect console.writeline from windows application to a string

It basically amounts to the following:

var originalConsoleOut = Console.Out; // preserve the original stream
using(var writer = new StringWriter())
{
    Console.SetOut(writer);

    Console.WriteLine("some stuff"); // or make your DLL calls :)

    writer.Flush(); // when you're done, make sure everything is written out

    var myString = writer.GetStringBuilder().ToString();
}

Console.SetOut(originalConsoleOut); // restore Console.Out

So in your case you'd set this up before making calls to your third-party DLL.


As it seems like you want to catch the Console output in realtime, I figured out that you might create your own TextWriter implementation that fires an event whenever a Write or WriteLine happens on the Console.

The writer looks like this:

    public class ConsoleWriterEventArgs : EventArgs
    {
        public string Value { get; private set; }
        public ConsoleWriterEventArgs(string value)
        {
            Value = value;
        }
    }

    public class ConsoleWriter : TextWriter
    {
        public override Encoding Encoding { get { return Encoding.UTF8; } }

        public override void Write(string value)
        {
            if (WriteEvent != null) WriteEvent(this, new ConsoleWriterEventArgs(value));
            base.Write(value);
        }

        public override void WriteLine(string value)
        {
            if (WriteLineEvent != null) WriteLineEvent(this, new ConsoleWriterEventArgs(value));
            base.WriteLine(value);
        }

        public event EventHandler<ConsoleWriterEventArgs> WriteEvent;
        public event EventHandler<ConsoleWriterEventArgs> WriteLineEvent;
    }

If it's a WinForm app, you can setup the writer and consume its events in the Program.cs like this:

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        using (var consoleWriter = new ConsoleWriter())
        {
            consoleWriter.WriteEvent += consoleWriter_WriteEvent;
            consoleWriter.WriteLineEvent += consoleWriter_WriteLineEvent;

            Console.SetOut(consoleWriter);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

    static void consoleWriter_WriteLineEvent(object sender, Program.ConsoleWriterEventArgs e)
    {
        MessageBox.Show(e.Value, "WriteLine");
    }

    static void consoleWriter_WriteEvent(object sender, Program.ConsoleWriterEventArgs e)
    {
        MessageBox.Show(e.Value, "Write");
    }

You can also call SetOut with Console.OpenStandardOutput, this will restore the original output stream:

Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));

Tags:

C#

.Net

Console