如何将所有控制台输出放在一个文件中,但也将其显示在控制台 C# 上?

How to put all console output in a file but also display it on console C#?

我如何在 C# 中执行此操作?我知道 Console.SetOut() 但这不是我想要的,因为我的控制台上什么也没有,所有东西都归档了。我如何才能既写入文本文件又显示在控制台上?有没有什么聪明的方法,或者我需要在每个 Console.WriteLine() 函数

你可以使用一个简单的记录器class:

class Logger {
    string LogFilePath { get; set; }

    void WriteLine(string msg) {
        Console.WriteLine(msg);
        System.IO.File.AppendAllText(LogFilePath, msg + '\n');
    }
}

用法:

var logger = new Logger { LogFilePath = "text file path" };
logger.WriteLine("Write this to the console and append to the logfile");