title: System.ObjectDisposedException: 'Cannot write to a closed TextWriter.' Error in SetOut
body: <p>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 </p>
  
  <blockquote>
    <p>System.ObjectDisposedException: 'Cannot write to a closed TextWriter.' </p>
  </blockquote>
  
  <p>Here is the code: </p>
  
  <pre><code>string[] files = Directory.GetFiles(@"C:\CSA FIles(test)\", "*.*", 
                                      SearchOption.AllDirectories);
  
          foreach (string file in files)
          {
  
              if (File.GetLastWriteTime(file)
                  &lt; 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);
                   }`
  </code></pre>