C#创建具有多个文件的ZIP存档 [英] C# Create ZIP Archive with multiple files

查看:123
本文介绍了C#创建具有多个文件的ZIP存档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试创建具有多个文本文件的ZIP存档,如下所示:

I'm trying to create a ZIP archive with multiple text files as follows:

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文件,怎么了?

However, the ZIP is created with only the last text file, what's wrong?

推荐答案

您要在每次迭代中创建 ZipArchive 。交换 foreach 使用应该可以解决此问题:

You are creating ZipArchive on each iteration. Swapping foreach and using should solve it:

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

这篇关于C#创建具有多个文件的ZIP存档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆