How do I dispose my filestream when implementing a file download in ASP.NET?

后端 未结 2 1214
醉酒成梦
醉酒成梦 2020-11-27 06:40

I have a class DocumentGenerator which wraps a MemoryStream. So I have implemented IDisposable on the class.

I can\'t see how/

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 06:57

    Just to add to what Darin has said, it's important to note this concept:

    public Stream GetDownloadFile(...)
    {
      using (var stream = new MemoryStream()) {
        return stream;
      }
    }
    
    public Stream GetDownloadFile(...)
    {
      using (var generator = DocumentGenerator.OpenTemplate(path))
      {
        // Document manipulation.
    
        return File(generator.GetDocumentStream(), "text/plain", filename);
      }
    }
    

    Regardless of how you are using it in your method, the using block ensures that Dispose is always called, this is important when you consider to use the result of the using block as a return statement, it won't stop it from being disposed....

提交回复
热议问题