如何保存控制台应用程序的输出 [英] How to save the output of a console application

查看:273
本文介绍了如何保存控制台应用程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要如何让我的C#控制台应用程序通过标准输出显示文本给用户的建议,同时仍然能够访问它。我想实现的实际功能是在程序执行结束时将整个输出缓冲区转储到一个文本文件。

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.

我使用的解决方法,找到一个更清洁的方法是子类 TextWriter 覆盖写入方法,所以他们都写入文件并调用原始的stdout writer。类似这样:

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

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
    }
  }
}


b $ b

查看它写入和刷新文件所有的时间。我想只在执行结束时才这样做,但是我找不到任何方式访问输出缓冲区。

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.

另外,不准确的

推荐答案

完美的解决方案因为这是使用控制台附加程序和文件附加程序的 log4net 。还有许多其他appender可用。它还允许您在运行时关闭和打开不同的appender。

The perfect solution for this is to use log4net 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.

这篇关于如何保存控制台应用程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆