gpt4 book ai didi

asp.net-mvc - 在 MVC 中使用内存流和 DotNetZip 给出 "Cannot access a closed Stream"

转载 作者:行者123 更新时间:2023-12-02 11:03:18 25 4
gpt4 key购买 nike

我正在尝试使用 DotNetZip 组件在 MVC 方法中创建 zip 文件。

这是我的代码:

    public FileResult DownloadImagefilesAsZip()
{
using (var memoryStream = new MemoryStream())
{
using (var zip = new ZipFile())
{
zip.AddDirectory(Server.MapPath("/Images/"));
zip.Save(memoryStream);

return File(memoryStream, "gzip", "images.zip");
}
}
}

当我运行它时,我收到“无法访问关闭的流”错误,我不知道为什么。

最佳答案

不要丢弃MemoryStreamFileStreamResult将在完成将其写入响应后处理:

public ActionResult DownloadImagefilesAsZip()
{
var memoryStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddDirectory(Server.MapPath("~/Images"));
zip.Save(memoryStream);
return File(memoryStream, "application/gzip", "images.zip");
}
}

顺便说一句,我建议您编写自定义操作结果来处理此问题,而不是在 Controller 操作中编写管道代码。您不仅会得到可重用的操作结果,而且请记住您的代码效率非常低=>您正在内存中执行 ZIP 操作,从而将整个 ~/images 目录内容 + zip 文件加载到内存中。如果这个目录中有很多用户和很多文件,你很快就会耗尽内存。

更有效的解决方案是直接写入响应流:

public class ZipResult : ActionResult
{
public string Path { get; private set; }
public string Filename { get; private set; }

public ZipResult(string path, string filename)
{
Path = path;
Filename = filename;
}

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

var response = context.HttpContext.Response;
response.ContentType = "application/gzip";
using (var zip = new ZipFile())
{
zip.AddDirectory(Path);
zip.Save(response.OutputStream);
var cd = new ContentDisposition
{
FileName = Filename,
Inline = false
};
response.Headers.Add("Content-Disposition", cd.ToString());
}
}
}

然后:

public ActionResult DownloadImagefilesAsZip()
{
return new ZipResult(Server.MapPath("~/Images"), "images.zip");
}

关于asp.net-mvc - 在 MVC 中使用内存流和 DotNetZip 给出 "Cannot access a closed Stream",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12919785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com