Redirect console.writeline from windows application to a string

前端 未结 4 1804
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 08:29

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.

4条回答
  •  被撕碎了的回忆
    2020-11-28 08:53

    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.

提交回复
热议问题