当尝试使用Ionic.Zip dll下载多个文件作为Zip文件时,OutOfMemory异常
本文关键字:Zip 文件 异常 OutOfMemory 下载 Ionic dll | 更新日期: 2023-09-27 17:49:23
这是我用来使用Ionic.Zip
dll下载多个文件作为zip文件的工作代码。文件内容存储在SQL数据库中。如果我尝试一次下载1-2个文件,这个程序就会工作,但是如果我尝试下载多个文件,就会抛出OutOfMemory
异常,因为有些文件可能非常大。
试图写入outputStream
时发生异常。
如何改进此代码以下载多个文件,或者是否有更好的方法逐个下载多个文件,而不是将它们压缩到一个大文件?
代码:public ActionResult DownloadMultipleFiles()
{
string connectionString = "MY DB CONNECTIOBN STRING";
List<Document> documents = new List<Document>();
var query = "MY LIST OF FILES - FILE METADA DATA LIKE FILEID, FILENAME";
documents = query.Query<Document>(connectionString1).ToList();
List<Document> DOCS = documents.GetRange(0, 50); // 50 FILES
Response.Clear();
var outputStream = new MemoryStream();
using (var zip = new ZipFile())
{
foreach (var doc in DOCS)
{
Stream stream = new MemoryStream();
byte[] content = GetFileContent(doc.FileContentId); // This method returns file content
stream.Write(content, 0, content.Length);
zip.UseZip64WhenSaving = Zip64Option.AsNecessary // edited
zip.AddEntry(doc.FileName, content);
}
zip.Save(outputStream);
}
return File(outputStream, "application/zip", "allFiles.zip");
}
将文件下载到磁盘而不是内存中,然后使用Ionic将它们从磁盘中压缩。这意味着您不需要一次将所有文件放在内存中。