繁体   English   中英

使用DotNetZip库在内存中嵌套Zip文件和文件夹

[英]Nesting Zip Files and Folders in Memory using DotNetZip Library

我们有一个页面,用户可以下载媒体,并构建类似于以下内容的文件夹结构,然后将其压缩并在响应中发送回给用户。

ZippedFolder.zip
    - Folder A
         - File 1
         - File 2
    - Folder B
         - File 3
         - File 4

完成此任务的现有实现将文件和目录临时保存到文件系统,然后最后将其删除。 我们正在努力摆脱这种困扰,并希望在内存中完全做到这一点。

我能够成功创建其中包含文件的ZipFile,但是我遇到的问题是创建文件夹A文件夹B并将文件添加到其中,然后将这两个文件夹添加到Zip文件中。

如何在不保存到文件系统的情况下执行此操作?

下面是仅将文件流保存到zip文件,然后在响应上设置Output Stream的代码。

public Stream CompressStreams(IList<Stream> Streams, IList<string> StreamNames, Stream OutputStream = null)
    {
        MemoryStream Response = null;

        using (ZipFile ZippedFile = new ZipFile())
        {
            for (int i = 0, length = Streams.Count; i < length; i++)
            {
                ZippedFile.AddEntry(StreamNames[i], Streams[i]);
            }
            if (OutputStream != null)
            {
                ZippedFile.Save(OutputStream);
            }
            else
            {
                Response = new MemoryStream();
                ZippedFile.Save(Response);
                // Move the stream back to the beginning for reading
                Response.Seek(0, SeekOrigin.Begin);
            }
        }
        return Response;
    }

编辑我们正在使用DotNetZip作为压缩/解压缩库。

这是使用System.IO.Compression.ZipArchive的另一种方法

public Stream CompressStreams(IList<Stream> Streams, IList<string> StreamNames, Stream OutputStream = null)
    {
        MemoryStream Response = new MemoryStream();

        using (ZipArchive ZippedFile = new ZipArchive(Response, ZipArchiveMode.Create, true))
        {
            for (int i = 0, length = Streams.Count; i < length; i++)
                using (var entry = ZippedFile.CreateEntry(StreamNames[i]).Open())
                {
                    Streams[i].CopyTo(entry);
                }

        }
        if (OutputStream != null)
        {
            Response.Seek(0, SeekOrigin.Begin);
            Response.CopyTo(OutputStream);
        }

        return Response;
    }

和一点测试:

        using (var write = new FileStream(@"C:\users\Public\Desktop\Testzip.zip", FileMode.OpenOrCreate, FileAccess.Write))
        using (var read = new FileStream(@"C:\windows\System32\drivers\etc\hosts", FileMode.Open, FileAccess.Read))
        {
            CompressStreams(new List<Stream>() { read }, new List<string>() { @"A\One.txt" }, write);
        }

回复:您的评论-对不起,不确定它是否在后台创建了某些东西,但您自己创建它并不是为了做任何事情

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM