gpt4 book ai didi

c# - ZipArchive 返回空文件夹 C#

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:28 27 4
gpt4 key购买 nike

我正在使用 ZipArchive 为文档列表创建压缩文件夹。

我不明白为什么,当我返回存档文件夹时它是空的。

有没有人看到我在这里做错了什么?

我的代码如下:

if (files.Count > 1)
{
var ms = new MemoryStream();
var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, false);
foreach (var file in files)
{
var entry = zipArchive.CreateEntry(file.UploadFileName, CompressionLevel.Fastest);
using (var streamWriter = new StreamWriter(entry.Open()))
{
Stream strFile = new MemoryStream(file.UploadFileBytesStream);
streamWriter.Write(strFile);
strFile.CopyTo(ms);
}
}
return File(ms, System.Net.Mime.MediaTypeNames.Application.Zip, "FinancialActivityReports.zip");
}

最佳答案

假设以下模型为 file

public class FileModel {
public string UploadFileName { get; set; }
public byte[] UploadFileBytesStream { get; set; }
}

编写了以下帮助程序来创建压缩文件流

public static class FileModelCompression {

public static Stream Compress(this IEnumerable<FileModel> files) {
if (files.Any()) {
var ms = new MemoryStream();
var archive = new ZipArchive(ms, ZipArchiveMode.Create, false);
foreach (var file in files) {
var entry = archive.add(file);
}
ms.Position = 0;
return ms;
}
return null;
}

private static ZipArchiveEntry add(this ZipArchive archive, FileModel file) {
var entry = archive.CreateEntry(file.UploadFileName, CompressionLevel.Fastest);
using (var stream = entry.Open()) {
stream.Write(file.UploadFileBytesStream, 0, file.UploadFileBytesStream.Length);
stream.Position = 0;
stream.Close();
}
return entry;
}
}

假设 files,您编写代码源自 IEnumerable<FileModel>然后将更改为...

if (files.Count > 1)
{
var stream = files.Compress();
return File(stream, System.Net.Mime.MediaTypeNames.Application.Zip, "FinancialActivityReports.zip");
}

关于c# - ZipArchive 返回空文件夹 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36776704/

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