加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何压缩zip文件中的多个文件

发布时间:2020-12-15 18:28:29 所属栏目:百科 来源:网络整理
导读:我正在尝试将两个文本文件压缩为zip文件.这是我的公共方法的样子: public ActionResult Index(){ byte[] file1 = System.IO.File.ReadAllBytes(@"C:file1.txt"); byte[] file2 = System.IO.File.ReadAllBytes(@"C:file2.txt"); Dictionarystring,byte[] f
我正在尝试将两个文本文件压缩为zip文件.这是我的公共方法的样子:
public ActionResult Index()
{

    byte[] file1 = System.IO.File.ReadAllBytes(@"C:file1.txt");
    byte[] file2 = System.IO.File.ReadAllBytes(@"C:file2.txt");
    Dictionary<string,byte[]> fileList = new Dictionary<string,byte[]>();
    fileList.Add("file1.txt",file1);
    fileList.Add("file2.txt",file2);
    CompressToZip("zip.zip",fileList);

    return View();
}

这就是我的压缩方法的样子:

private void CompressToZip(string fileName,Dictionary<string,byte[]> fileList)
{
    using (var memoryStream = new MemoryStream())
    {
        foreach (var file in fileList)
        {
            using (var archive = new ZipArchive(memoryStream,ZipArchiveMode.Create,true))
            {
                var demoFile = archive.CreateEntry(file.Key);

                using (var entryStream = demoFile.Open())
                using (var b = new BinaryWriter(entryStream))
                {
                    b.Write(file.Value);
                }
            }
        }

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

}

在这种方法中,完美地创建了zip文件夹.但问题是我在zip文件夹中只得到一个文件(只有第二个文件将在zip文件夹中创建).
没有发现错误.

Question: How to compress both text files into the zip folder?

先谢谢你!

解决方法

您的代码实际上将两个单独的zip存档保存到zip.zip文件中(为每个要压缩的文件创建一个新的ZipArchive).第一个zip存档仅包含file1.txt,第二个仅包含file2.txt.在Windows资源管理器中打开zip.zip时,它只显示第二个zip存档的内容.

要创建包含两个文件的单个zip存档,只需在FileList循环之外移动ZipArchive的创建:

using (var archive = new ZipArchive(memoryStream,true))
{
    foreach (var file in fileList)
    {                    
        var demoFile = archive.CreateEntry(file.Key);

        using (var entryStream = demoFile.Open())
        using (var b = new BinaryWriter(entryStream))
        {
            b.Write(file.Value);
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读