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?



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


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;


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;




You can create TextWriter

one that does nothing:

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


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


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



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


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





All Articles