System.ObjectDisposedException: 'Cannot write to a closed TextWriter.' SetOut 错误

System.ObjectDisposedException: 'Cannot write to a closed TextWriter.' Error in SetOut

我正在编写一个程序,可以查看文件夹内的所有文件,然后将控制台输出写入一个新的 txt 文件,但是当我 运行 程序在写入 1 行后,它会产生一个错误提示

System.ObjectDisposedException: 'Cannot write to a closed TextWriter.'

代码如下:

string[] files = Directory.GetFiles(@"C:\CSA FIles(test)\", "*.*", 
                                    SearchOption.AllDirectories);

        foreach (string file in files)
        {

            if (File.GetLastWriteTime(file)
                < DateTime.Now.AddMonths(-3))
            {

               Console.WriteLine(file);


                using (StreamWriter writer = new StreamWriter(@"C:\for checking\sample.txt"))
                 {
                     Console.SetOut(writer);
                     Act();
                 }
                 void Act()
                 {
                     Console.WriteLine(file);
                 }`

正如 Ron 在他的评论中所说,StreamWriter 对象在被处理的同时仍被 Console 使用。最好在您的 StreamWriter 被处理之前恢复原始流。

using (StreamWriter writer = new StreamWriter(@"C:\for checking\sample.txt"))
{
    var originalStream = Console.Out;
    Console.SetOut(writer);
    Act();
    Console.SetOut(originalStream);
} //writer object is disposed here

Microsoft 提供示例 here