Suppress 3rd party library console output?

假装没事ソ 提交于 2019-12-20 11:51:09

问题


I need to call a 3rd party library that happens to spew a bunch of stuff to the console. The code simply like this...

int MyMethod(int a)
{
   int b = ThirdPartyLibrary.Transform(a);  // spews unwanted console output
   return b;
}

Is there an easy way to suppress the unwanted console output from ThirdPartyLibrary? For performance reasons, new processes or threads cannot be used in the solution.


回答1:


Well you can use Console.SetOut to an implementation of TextWriter which doesn't write anywhere:

Console.SetOut(TextWriter.Null);

That will suppress all console output though. You could always maintain a reference to the original Console.Out writer and use that for your own output.




回答2:


Here's one way to do it (which also usually covers managed C++ applications that you P/Invoke from C# or otherwise):

internal class OutputSink : IDisposable
{
    [DllImport("kernel32.dll")]
    public static extern IntPtr GetStdHandle(int nStdHandle);

    [DllImport("kernel32.dll")]
    public static extern int SetStdHandle(int nStdHandle, IntPtr hHandle);

    private readonly TextWriter _oldOut;
    private readonly TextWriter _oldError;
    private readonly IntPtr _oldOutHandle;
    private readonly IntPtr _oldErrorHandle;

    public OutputSink()
    {
        _oldOutHandle = GetStdHandle(-11);
        _oldErrorHandle = GetStdHandle(-12);
        _oldOut = Console.Out;
        _oldError = Console.Error;
        Console.SetOut(TextWriter.Null);
        Console.SetError(TextWriter.Null);
        SetStdHandle(-11, IntPtr.Zero);
        SetStdHandle(-12, IntPtr.Zero);
    }

    public void Dispose()
    {
        SetStdHandle(-11, _oldOutHandle);
        SetStdHandle(-12, _oldErrorHandle);
        Console.SetOut(_oldOut);
        Console.SetError(_oldError);
    }
}

This class can be called as follows:

using (new OutputSink())
{
    /* Call 3rd party library here... */
}

This will have an impact. Any application logic that tries to use the console from another thread during the time you are using the OutputSink will not function correctly to write to the standard output, standard error, console output, or console error.



来源:https://stackoverflow.com/questions/1412288/suppress-3rd-party-library-console-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!