如何在 C# 中将字节数组转换为 zip 存档?
how to convert byte array to zip archive in c#?
我在数据库中有一个 ziparchive 的字节数组。当我从数据库中检索数据并尝试转换回 Ziparchive 时,它会抛出错误。有没有办法从字节数组转换为 zipArchive?
据此answer我认为可以将您的流字节数组转换为 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);
}
}
}
}
return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
}
在这里,使用 new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
行,如果您已经转换为 zip 文件,那么您可以像这样将流字节数组转换为 zip 存档:
new FileContentResult(your_stream_byte_array, "application/zip") { FileDownloadName = "Filename.zip" };
我在数据库中有一个 ziparchive 的字节数组。当我从数据库中检索数据并尝试转换回 Ziparchive 时,它会抛出错误。有没有办法从字节数组转换为 zipArchive?
据此answer我认为可以将您的流字节数组转换为 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);
}
}
}
}
return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
}
在这里,使用 new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
行,如果您已经转换为 zip 文件,那么您可以像这样将流字节数组转换为 zip 存档:
new FileContentResult(your_stream_byte_array, "application/zip") { FileDownloadName = "Filename.zip" };