title: How do I dispose my filestream when implementing a file download in ASP.NET?
body: <p>I have a class <code>DocumentGenerator</code> which wraps a <code>MemoryStream</code>. So I have implemented <code>IDisposable</code> on the class.</p>
  
  <p>I can't see how/where I can possibly dispose it though.</p>
  
  <p>This is my current code, which performs a file download in MVC:</p>
  
  <pre><code>using (DocumentGenerator dg = DocumentGenerator.OpenTemplate(path))
  {
      /* some document manipulation with the 
         DocumentGenerator goes here ...*/
  
      return File(dg.GetDocumentStream(), "text/plain", filename);
  }
  </code></pre>
  
  <p>This errors as the stream is closed/disposed before the controller has finished with it. How can I make sure my resources are properly disposed in this situation?</p>
  
  <p><strong>EDIT:</strong> My implementation of <code>IDisposable</code> at the moment just disposes the <code>MemoryStream</code>. I know it's not a proper implementation, I just used it as a test. Is there something different I could do here to make it work?</p>
  
  <pre><code>public void Dispose()
  {
      _ms.Dispose();
      _ms = null;
  }
  </code></pre>