通过对@rene的评论,我找到了一个有效的答案。他说:
如果不处理
MemoryStream
不要打电话接近它。可能是在调用Save之前才读取实际内存流。在您的代码中,所有这些流都已经被关闭、释放,甚至可能被GC’d。
请参见我的代码。
using Ionic.Zip;
using System.IO;
using System.Net;
[HttpPost]
public ActionResult Downloads(string lang, string product, IEnumerable<string> file, string action)
{
string zipname = "manuals.zip";
List<MemoryStream> streams = new List<MemoryStream>();
using (ZipFile zip = new ZipFile())
{
foreach (string f in file.Distinct())
{
using (WebClient client = new WebClient())
{
MemoryStream output = new MemoryStream();
byte[] b = client.DownloadData(f);
output.Write(b, 0, b.Length);
output.Flush();
output.Position = 0;
zip.AddEntry(f.Split('/').Last(), output);
// output.Close(); // â removed this line
streams.Add(output);
}
}
Response.Clear();
Response.ContentType = "application/zip, application/octet-stream";
Response.AddHeader("content-disposition", $"attachment; filename={product.Replace('/', '-')}-{zipname}");
zip.Save(Response.OutputStream);
foreach (MemoryStream stream in streams)
{
stream.Close();
stream.Dispose();
}
Response.End();
}
}
为了确保所有流都已关闭,我添加了所有打开的
内存流
s到列表和之前
Response.End();
,我走近去把它们都处理掉。