c# - 在 ASP.NET 中实现文件下载时如何处理我的文件流?

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

此错误是因为在 Controller 完成流之前关闭/处置流。在这种情况下,如何确保我的资源得到妥善处理?

编辑:我目前的IDisposable 实现只是处理MemoryStream。我知道这不是一个正确的实现,我只是将它用作测试。我可以在这里做些不同的事情来让它发挥作用吗?

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

最佳答案

您不需要处理流。它将由 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)这会从您的 Controller 调用构造函数,该构造函数将流存储到在渲染期间处理的公共(public)属性中。

结论:您不必担心处理使用 dg.GetDocumentStream() 获取的流.

关于c# - 在 ASP.NET 中实现文件下载时如何处理我的文件流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3084366/

相关文章:

asp.net-mvc - 如何在 ASP MVC 应用程序中映射文件夹的路径

asp.net-mvc - ASP.NET MVC 4 : Handle exception caused by JsonValueProvider

c# - 如何使用中间件代替 Controller 初始化?

c# - 优化 if 和 foreach 的 null 检查

c# - 如何在 TreeView 控件中显示滚动条

javascript - Internet Explorer 将 e.which 显示为未定义

c# - 用户事件记录、遥测(和全局异常处理程序中的变量)

IE 10 上每个页面中的 Javascript 错误

javascript - 有关正则表达式中的单引号和双引号的问题吗?

c# - MVC C# 自定义 MvcRouteHandler - 如何?