好的,所以这里的想法是更改控制台输入和输出的读取器/写入器,以执行它们之前所做的操作,同时写入日志文件。我创建了一个 Log 类,它可能应该被扩展以便将文件名/路径作为参数,但重要的是要有一个这样才能同步输出流。
public class Log
{
private StreamWriter output;
public Log()
{
output = new StreamWriter(File.OpenWrite("output.txt"));
}
public void Write(char c)
{
lock (output)
{
output.Write(c);
}
}
public void Close()
{
output.Close();
}
}
public class MyConsoleOutput : TextWriter
{
private TextWriter standard;
private Log log;
public MyConsoleOutput(TextWriter standard, Log log)
{
this.standard = standard;
this.log = log;
}
public override void Write(char value)
{
standard.Write(value);
log.Write(value);
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
protected override void Dispose(bool disposing)
{
standard.Dispose();
}
}
public class MyConsoleInput : TextReader
{
private TextReader standard;
private Log log;
public MyConsoleInput(TextReader standard, Log log)
{
this.standard = standard;
this.log = log;
}
public override int Peek()
{
return standard.Peek();
}
public override int Read()
{
int result = standard.Read();
log.Write((char)result);
return result;
}
protected override void Dispose(bool disposing)
{
standard.Dispose();
}
}
现在我们已经创建了这些类,我们将在开始时执行以下操作Main
:
Log log = new Log();
Console.SetOut(new MyConsoleOutput(Console.Out, log));
Console.SetIn(new MyConsoleInput(Console.In, log));
我们在结尾处也需要这个Main
:
log.Close();
这是一个有点快速和肮脏的写作。如果您在生产中使用它,您可能需要更改很多类/方法名称。