我需要关于如何通过标准输出有我的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
覆盖的写作方法,使他们既能写一个文件,并调用原来的标准输出作家。事情是这样的:
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
}
}
}
看到它写入并刷新该文件的所有时间。我喜欢只在执行结束做到这一点,但我无法找到任何方式来访问输出缓冲区。
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.
此外,借口不准确上述code(不得不写的临时的,抱歉)。
Also, excuse inaccuracies with the above code (had to write it ad hoc, sorry ;).
对于这个完美的解决方案是使用 log4net的与控制台附加目的地和文件附加目的地。有很多可用的其他附加目的地也是如此。它还允许你把不同的附加目的地关闭,在运行时。
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.