在ASP.NET中实现文件下载时如何处理文件流?

时间:2010-06-21 11:53:44

标签: c# asp.net asp.net-mvc streaming idisposable

我有一个包含DocumentGenerator的课程MemoryStream。所以我在课堂上实现了IDisposable

我看不出如何/在哪里可以处理它。

这是我当前的代码,它在MVC中执行文件下载:

using (DocumentGenerator dg = DocumentGenerator.OpenTemplate(path))
{
    /* some document manipulation with the 
       DocumentGenerator goes here ...*/

    return File(dg.GetDocumentStream(), "text/plain", filename);
}

在控制器完成之前关闭/处理流时出现此错误。在这种情况下,如何确保我的资源得到妥善处理?

编辑:目前我IDisposable的实施只是处理了MemoryStream。我知道这不是一个正确的实现,我只是用它作为测试。我能在这里做些什么来让它起作用吗?

public void Dispose()
{
    _ms.Dispose();
    _ms = null;
}

2 个答案:

答案 0 :(得分:32)

您不需要处理流。它将通过FileStreamResult.WriteFile方法处理。该类摘录:

public FileStreamResult(Stream fileStream, string contentType) : base(contentType)
{
    if (fileStream == null)
    {
        throw new ArgumentNullException("fileStream");
    }
    this.FileStream = fileStream;
}

protected override void WriteFile(HttpResponseBase response)
{
    Stream outputStream = response.OutputStream;
    using (this.FileStream)
    {
        byte[] buffer = new byte[0x1000];
        while (true)
        {
            int count = this.FileStream.Read(buffer, 0, 0x1000);
            if (count == 0)
            {
                return;
            }
            outputStream.Write(buffer, 0, count);
        }
    }
}

注意using。当您从控制器调用File(dg.GetDocumentStream(), "text/plain", filename)时,它会调用构造函数,该构造函数将流存储到在呈现期间处置的公共属性中。

结论:您无需担心使用dg.GetDocumentStream()处理获取的流。

答案 1 :(得分:0)

只是要添加Darin has said,重要的是要注意这个概念:

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);
  }
}

无论你如何在你的方法中使用它,using块确保始终调用Dispose,当你考虑使用using块的结果作为return语句时,这很重要,它不会阻止它被处置......