简体   繁体   English

C#使用多个文件创建ZIP存档

[英]C# Create ZIP Archive with multiple files

I'm trying to create a ZIP archive with multiple text files as follows: 我正在尝试使用多个文本文件创建ZIP存档,如下所示:

Dictionary<string, string> Values = new Dictionary<string, string>();
using (var memoryStream = new MemoryStream())
{
    string zip = @"C:\Temp\ZipFile.zip";
    foreach (var item in Values)
    {
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            var file = archive.CreateEntry(item.Key + ".txt");
            using (var entryStream = file.Open())
            using (var streamWriter = new StreamWriter(entryStream))
            {
                streamWriter.Write(item.Value);
            }
        }
    }
    using (var fileStream = new FileStream(zip, FileMode.Create))
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}

However, the ZIP is created with only the last text file, what's wrong? 但是,ZIP仅使用最后一个文本文件创建,出了什么问题?

You are creating ZipArchive on each iteration. 您正在每次迭代时创建ZipArchive Swapping foreach and using should solve it: 交换foreachusing应该解决它:

Dictionary<string, string> Values = new Dictionary<string, string>();
using (var memoryStream = new MemoryStream())
{
    string zip = @"C:\Temp\ZipFile.zip";
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        foreach (var item in Values)
        {
            var file = archive.CreateEntry(item.Key + ".txt");
            using (var entryStream = file.Open())
            using (var streamWriter = new StreamWriter(entryStream))
            {
                streamWriter.Write(item.Value);
            }
        }
    }

    using (var fileStream = new FileStream(zip, FileMode.Create))
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}

Each time your foreach loop runs it has the ZipArchiveMode as Create. 每次foreach循环运行时,ZipArchiveMode都为Create。 That should be the problem, so it generates new zip everytime with new content on it, such as the last text file. 这应该是问题所在,因此每次都会生成新的zip,其中包含新内容,例如最后一个文本文件。 Create an exception for each loop run after the first one it should be solved. 在应该解决的第一个循环之后为每个循环运行创建一个异常。

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

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