Jeff Key

It works on my machine

Sponsors

My Job

My stuff

Old stuff

Useful Stuff

NullTextWriter

I'm trying to do some profiling on a command line app that uses a number of assemblies that spit out a bunch of debug information via Console.WriteLine (this isn't the intent and the calls have since been removed; I just don't have the latest bits yet).  This is no problem on the command line, as I can redirect output to null via “> nul”.  Unfortunately, this doesn't work when started from a profiler.

The simple solution was to add an optional “-null” argument to the application.  When that argument is given, I replace the standard out with a NullTextWriter, then re-add the standard out at program end in case any exceptions were thrown, etc.  Here's the magic:

public class NullTextWriter : TextWriter  {
    
public override System.Text.Encoding Encoding  {
         
get { return ASCIIEncoding.Default; }
     }
}

You can set the output stream by calling Console.SetOut(TextWriter).  Works for me.

Posted: Nov 29 2003, 09:43 PM by jeffreykey | with 2 comment(s)
Filed under:

Comments

Brian Grunkemeyer said:

That's a good workaround. However, you should consider using TextWriter.Null instead of writing your own class. We were thinking ahead in V1, providing it for this exact purpose. (Unfortunately it is a static field, not a property. We forgot to fix once properties were supported by our compilers. But you can of course still use it, probably with identical syntax.)

- Brian
CLR Base Class Libraries team
# November 30, 2003 4:55 AM

Jeff Key said:

Wouldn't you know it. I don't have my beloved MSDN docs installed locally for a couple days and look what happens. Glad to know it's there for next next. Thanks!
# November 30, 2003 5:03 AM