Redirect console.writeline from windows application to a string

Viewed 22945

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.

5 Answers

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
}
Related