Search code examples
c#streamwriterconsole.setout

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


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

Solution

  • 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.