geogeek
geogeek

Reputation: 1302

Redirect console.writeline from windows application to a string

I have an external dll written in C# and I studied from the assemblies documentation that it writes its debug messages to the Console using Console.WriteLine.

this DLL writes to console during my interaction with the UI of the Application, so i don't make DLL calls directly, but i would capture all console output , so i think i got to intialize in form load , then get that captured text later.

I would like to redirect all the output to a string variable.

I tried Console.SetOut, but its use to redirect to string is not easy.

Upvotes: 21

Views: 27086

Answers (5)

PolarBear
PolarBear

Reputation: 1267

Using solutions proposed by @Adam Lear and @Carlo V. Dango I created a helper class:

public sealed class RedirectConsole : IDisposable
{
    private readonly Action<string> logFunction;
    private readonly TextWriter oldOut = Console.Out;
    private readonly StringWriter sw = new StringWriter();

    public RedirectConsole(Action<string> logFunction)
    {
        this.logFunction = logFunction;
        Console.SetOut(sw);
    }

    public void Dispose()
    {
        Console.SetOut(oldOut);
        sw.Flush();
        logFunction(sw.ToString());
        sw.Dispose();
    }
}

which can be used in the following way:

public static void MyWrite(string str)
{
    // print console output to Log/Socket/File
}

public static void Main()
{
    using(var r = new RedirectConsole(MyWrite)) {
        Console.WriteLine("Message 1");
        Console.WriteLine("Message 2");
    }
    // After the using section is finished,
    // MyWrite will be called once with a string containing all messages,
    // which has been written during the using section,
    // separated by new line characters
}

Upvotes: 0

Ricardo Peres
Ricardo Peres

Reputation: 14535

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

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

Upvotes: 5

Carlo V. Dango
Carlo V. Dango

Reputation: 13832

Or you can wrap it up in a helper method that takes some code as an argument run it and returns the string that was printed. Notice how we gracefully handle exceptions.

public string RunCodeReturnConsoleOut(Action code) 
{
  string result;
  var originalConsoleOut = Console.Out;
  try 
  {
    using (var writer = new StringWriter()) 
    {
      Console.SetOut(writer);
      code();
      writer.Flush();
      result = writer.GetStringBuilder().ToString();
    }
    return result;
  }
  finally 
  {
    Console.SetOut(originalConsoleOut); 
  }
}

Upvotes: 2

huysentruitw
huysentruitw

Reputation: 28111

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");
    }

Upvotes: 38

Adam Lear
Adam Lear

Reputation: 38768

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.

Upvotes: 23

Related Questions