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

2.2k Views Asked by At

I'm writing a program that can view all files inside a folder then write the console output to a new txt file but when I run the program after writing 1 line, it produces an error saying

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

Here is the code:

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);
                 }`
1

There are 1 best solutions below

2
On BEST ANSWER

As Ron says in his comment, the StreamWriter object is being disposed while still being used by Console. Best to reinstate the original stream before your StreamWriter is disposed.

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 provide an example here.