<p>I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution.</p>

<p>The workaround I use while I don't find a cleaner approach is to subclass <code>TextWriter</code> overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this:</p>

<pre><code>public class DirtyWorkaround {
  private class DirtyWriter : TextWriter {
    private TextWriter stdoutWriter;
    private StreamWriter fileWriter;

    public DirtyWriter(string path, TextWriter stdoutWriter) {
      this.stdoutWriter = stdoutWriter;
      this.fileWriter = new StreamWriter(path);
    }

    override public void Write(string s) {
      stdoutWriter.Write(s);

      fileWriter.Write(s);
      fileWriter.Flush();
    }

    // Same as above for WriteLine() and WriteLine(string),
    // plus whatever methods I need to override to inherit
    // from TextWriter (Encoding.Get I guess).
  }

  public static void Main(string[] args) {
    using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) {
      Console.SetOut(dw);

      // Teh codez
    }
  }
}
</code></pre>

<p>See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer.</p>

<p>Also, excuse inaccuracies with the above code (had to write it <em>ad hoc</em>, sorry ;).</p>

[{'answer_id': 61119, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 3, 'selected': False, 'text': "<p>I don't think there's anything wrong with your approach.</p>\n\n<p>If you wanted reusable code, consider implementing a class called <code>MultiWriter</code> or somesuch that takes as input two (or N?) <code>TextWriter</code> streams and distributes all writs, flushes, etc. to those streams.  Then you can do this file/console thing, but just as easily you can split any output stream.  Useful!</p>\n"}, {'answer_id': 61123, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 1, 'selected': False, 'text': '<p>Probably not what you want, but just in case... Apparently, <a href="http://en.wikipedia.org/wiki/Tee_(command)#Windows_PowerShell" rel="nofollow noreferrer">PowerShell implements</a> a version of the venerable <code>tee</code> command. Which is pretty much intended for exactly this purpose. So... smoke \'em if you got \'em.</p>\n'}, {'answer_id': 61134, 'author': 'Mike Schall', 'author_id': 4231, 'author_profile': 'https://Stackoverflow.com/users/4231', 'pm_score': 4, 'selected': True, 'text': '<p>The perfect solution for this is to use <a href="http://logging.apache.org/log4net/" rel="noreferrer">log4net</a> with a console appender and a file appender.  There are many other appenders available as well.  It also allows you to turn the different appenders off and on at runtime. </p>\n'}, {'answer_id': 61160, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 1, 'selected': False, 'text': '<p>I would say mimic the diagnostics that .NET itself uses (Trace and Debug).</p>\n\n<p>Create a "output" class that can have different classes that adhere to a text output interface. You report to the output class, it automatically sends the output given to the classes you have added (ConsoleOutput, TextFileOutput, WhateverOutput).. And so on.. This also leaves you open to add other "output" types (such as xml/xslt to get a nicely formatted report?).</p>\n\n<p>Check out the <a href="http://msdn.microsoft.com/en-us/library/sk36c28t.aspx" rel="nofollow noreferrer">Trace Listeners Collection</a> to see what I mean.</p>\n'}, {'answer_id': 61164, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 0, 'selected': False, 'text': "<p>Consider refactoring your application to separate the user-interaction portions from the business logic.  In my experience, such a separation is quite beneficial to the structure of your program.</p>\n\n<p>For the particular problem you're trying to solve here, it becomes straightforward for the user-interaction part to change its behavior from <code>Console.WriteLine</code> to file I/O.</p>\n"}, {'answer_id': 369254, 'author': 'Rob Parker', 'author_id': 181460, 'author_profile': 'https://Stackoverflow.com/users/181460', 'pm_score': 0, 'selected': False, 'text': "<p>I'm working on implementing a similar feature to capture output sent to the Console and save it to a log while still passing the output in real time to the normal Console so it doesn't break the application (eg. if it's a console application!).</p>\n\n<p>If you're still trying to do this in your own code by saving the console output (as opposed to using a logging system to save just the information you really care about), I think you can avoid the flush after each write, as long as you also override Flush() and make sure it flushes the original <code>stdoutWriter</code> you saved as well as your <code>fileWriter</code>.  You want to do this in case the application is trying to flush a partial line to the console for immediate display (such as an input prompt, a progress indicator, etc), to override the normal line-buffering.</p>\n\n<p>If that approach has problems with your console output being buffered too long, you might need to make sure that WriteLine() flushes <code>stdoutWriter</code> (but probably doesn't need to flush <code>fileWriter</code> except when your Flush() override is called).  But I would think that the original <code>Console.Out</code> (actually going to the console) would automatically flush its buffer upon a newline, so you shouldn't have to force it.</p>\n\n<p>You might also want to override Close() to (flush and) close your <code>fileWriter</code> (and probably <code>stdoutWriter</code> as well), but I'm not sure if that's really needed or if a Close() in the base TextWriter would issue a Flush() (which you would already override) and you might rely on application exit to close your file.  You should probably test that it gets flushed on exit, to be sure.  And be aware that an abnormal exit (crash) likely won't flush buffered output.  If that's an issue, flushing <code>fileWriter</code> on newline may be desirable, but that's another tricky can of worms to work out.</p>\n"}]
['https://Stackoverflow.com/questions/61110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4850/']