0

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);
                 }`
  • 2
    You are setting the console output to a stream, then closing that stream without setting it back to default. – Ron Beyer Oct 24 '18 at 03:55

1 Answers1

1

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.

  • Hi! It fixed the error but why is it that the text file has only 1 line written? – agentorange01 Oct 24 '18 at 05:30
  • The file is opened (and closed) each time around the loop. The file is cleared when its opened this way. Either alter the parameters to StreamWriter to append to an exiting file (see [this](https://stackoverflow.com/questions/7306214/append-lines-to-a-file-using-a-streamwriter) SO post) or put the using statement outside of the loop to open the file only once – Craig Thomas Oct 25 '18 at 00:48