ZipArchive 返回空文件夹 C#

ZipArchive returning Empty Folder C#

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

我不知道为什么,当我 return 我的存档文件夹是空的。

有人看到我做错了什么了吗?

我的代码如下:

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");
}