Redirect console output for only one method

I have a bunch of unit tests here. One of them expects the code to do nothing, because parsing the arguments shouldn't work.

Unfortunately, in this case, I am using forces in the parsing arguments library Console.Write()

and now my module outputs are being filled with library messages making them difficult to read.

Is there a way to redirect the console stdout to nothing (or a temporary file or whatever) before calling this method, and then redirect it back to stdout after it completes?

Thank!

Update

This is actually the error output that needs to be redirected ...

+3


source to share


2 answers


Yes, you can temporarily replace the output stream with a custom one. This can be done using the Console.SetOut () method . More or less (adaptation to your actual code, see also comments):

// We're not interested in its output, a NULL fake one may also work (better)
Console.SetOut(new StringWriter());

// Your code here...

// Now you have to restore default output stream
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);

      



UPDATE : As per your update (standard error stream redirection) you just need to replace *Out

with *Error

:

Console.SetError(new StringWriter());

// Your code here...

var standardError = new StreamWriter(Console.OpenStandardError());
standardError.AutoFlush = true;
Console.SetError(standardError);

      

+5


source


You can create TextWriter

one that does nothing:

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

      

Then you can install and restore the console output like this:



Console.WriteLine("Enabled");

var saved = Console.Out;
Console.SetOut(new NulTextWriter());
Console.WriteLine("This should not appear");

Console.SetOut(saved);
Console.WriteLine("Restored");

      

You can use the same approach to output the console error:

Console.Error.WriteLine("Enabled");

var saved = Console.Error;
Console.SetError(new NulTextWriter());
Console.Error.WriteLine("This should not appear");

Console.SetError(saved);
Console.Error.WriteLine("Restored");

      

+3


source







All Articles