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

时间:2014-11-24 05:19:49

标签: c# .net zip compression

我尝试使用多个文本文件创建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);
    }
}

但是,ZIP仅使用最后一个文本文件创建,这有什么不对?

2 个答案:

答案 0 :(得分:11)

您在每次迭代时都在创建ZipArchive。交换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);
    }
}

答案 1 :(得分:1)

每次foreach循环运行时,ZipArchiveMode都为Create。这应该是问题所在,因此每次都会生成新的zip,其中包含新内容,例如最后一个文本文件。在应该解决的第一个循环之后为每个循环运行创建一个异常。