ZipArchive returning Empty Folder C#

走远了吗. 提交于 2019-12-11 02:24:29

问题


I am using ZipArchive to create a zipped folder for a list of documents.

I cant figure out why, when I return my archived folder it is empty.

Does anyone see what I am doing wrong here?

My code is as follows:

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

回答1:


Assuming the following model for file

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

The following helper was written to create the stream of the compressed files

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

You code, assuming files is derived from IEnumerable<FileModel> will then change to this...

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


来源:https://stackoverflow.com/questions/36776704/ziparchive-returning-empty-folder-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!