从byte[]创建zip文件
本文关键字:zip 文件 创建 byte | 更新日期: 2023-09-27 18:19:09
我试图从一系列字节数组中创建。net 4.5 (System.IO.Compression)中的Zip文件。作为一个例子,从我使用的API中,我最终得到了一个List<Attachment>
,每个Attachment
都有一个称为Body
的属性,这是一个byte[]
。如何遍历该列表并创建包含每个附件的zip文件?
现在我的印象是,我必须将每个附件写入磁盘,并从中创建zip文件。
//This is great if I had the files on disk
ZipFile.CreateFromDirectory(startPath, zipPath);
//How can I create it from a series of byte arrays?
经过更多的游戏和阅读后,我能够弄清楚这一点。以下是如何创建包含多个文件的zip文件(存档),而无需向磁盘写入任何临时数据:
using (var compressedFileStream = new MemoryStream())
{
//Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, false)) {
foreach (var caseAttachmentModel in caseAttachmentModels) {
//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name);
//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body))
using (var zipEntryStream = zipEntry.Open()) {
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}
}
return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
}
这是op发布的公认答案的一个变体。然而,这是针对WebForms而不是MVC的。我正在工作的假设,caseAttachmentModel。正文是一个字节[]
基本上都是一样的,除了一个额外的方法,将zip作为响应发送出去。
using (var compressedFileStream = new MemoryStream()) {
//Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false)) {
foreach (var caseAttachmentModel in caseAttachmentModels) {
//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name);
//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body)) {
using (var zipEntryStream = zipEntry.Open()) {
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}
}
}
sendOutZIP(compressedFileStream.ToArray(), "FileName.zip");
}
private void sendOutZIP(byte[] zippedFiles, string filename)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/x-compressed";
Response.Charset = string.Empty;
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.BinaryWrite(zippedFiles);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.End();
}
我还想指出,@Levi Fuller在公认答案中关于参考文献的建议是正确的!
GZipStream和DeflateStream似乎可以让您使用流/字节数组来解决您的问题,但可能不是大多数用户可用的压缩文件格式。(例如,你的文件将有一个。gz扩展名)如果这个文件只在内部使用,那可能是可以的。
我不知道你如何使用微软的库来制作ZIP,但是我记得这个库支持一些你可能会觉得有用的东西:http://sevenzipsharp.codeplex.com/
根据LGPL授权