title: Cannot access a closed Stream while creating a downloadable text file in ASP MVC 3
body: <p>Im trying to prompt a downloadable text file (.txt), but I get this error:</p>
  
  <blockquote>
    <p>Cannot access a closed Stream.</p>
  </blockquote>
  
  <p>I have looked at simular questions in here:
  <a href="https://stackoverflow.com/questions/2331675/cannot-access-closed-stream">Cannot Access Closed Stream</a>
  But it was not very useful.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>    private FileStreamResult Export()
      {
          string name = "filename.txt";
  
          MemoryStream stream = new MemoryStream();
          using (StreamWriter writer = new StreamWriter(stream))
          {
              StringBuilder sb = new StringBuilder();
              sb.Append("A text...");
              writer.WriteLine(sb.ToString());
          }
  
          return File(stream, "text/plain", name);
      }
  </code></pre>
  
  <p><strong>UPDATE (working copy):</strong></p>
  
  <p>This gives me an blank text file.</p>
  
  <pre><code>private FileResult Export()
  {
      string name = "filename.txt";
  
      MemoryStream stream = new MemoryStream();
      StreamWriter writer = new StreamWriter(stream);
  
      StringBuilder sb = new StringBuilder();
      sb.Append("A text...");
      writer.WriteLine(sb.ToString());
  
      writer.Flush();
      stream.Seek(0, SeekOrigin.Begin);
  
      return File(stream, "text/plain", name);
  }
  </code></pre>