C# - 从ZIP中提取特定目录,保留文件夹结构

时间:2016-04-01 07:14:51

标签: c# .net zip compression

我有一个zip存档,存档内的文件夹结构如下所示:

+ dirA
  - fileA.txt
  + dirB
    - fileB.txt

我正在尝试将dirA的内容提取到磁盘,但在这样做的时候,我无法坚持文件夹结构,而不是

  - fileA.txt
  + dirB
    - fileB.txt

我得到了

  - fileA.txt
  - fileB.txt

这是我的代码:

using (ZipArchive archive = ZipFile.OpenRead(archivePath)) // archivePath is path to the zip archive
{
    // get the root directory
    var root = archive.Entries[0]?.FullName;
    if (root == null) { 
        // quit in a nice way
    }
    var result = from curr in archive.Entries
                 where Path.GetDirectoryName(curr.FullName) != root
                 where !string.IsNullOrEmpty(curr.Name)
                 select curr;

    foreach (ZipArchiveEntry entry in result)
    {
        string path = Path.Combine(extractPath, entry.Name); // extractPath is somwhere on the disk
        entry.ExtractToFile(path);
    }
}

我非常肯定,因为我在entry.Name中使用了entry.FullName而不是Path.Combine(),但如果我使用FullName,我会在路径中使用dirA目录ZipFile.ExtractToDirectory(archivePath, extractPath); 我试图不提取。 所以我在这里遇到了障碍,我能想到的唯一解决方案就是用以下方法解压缩整个拉链:

dirA

...然后将子文件夹从dirA移至其他位置并删除<c:forEach items="${List2}" var="alist"> <tr> <td> <input type="checkbox" name="check" value="${alist.check}"> </td> <td>${alist.two}</td> <td>${alist.three}</td> <td>${alist.four}</td> </tr> </c:forEach> <input type="radio" id="agree" value="Agree"/>Agree <input type="radio" id="disagree" value="Disagree"/> Disagree <input type="submit" value="Submit"/> 。这似乎不是最幸运的想法。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

您可以通过您不想要的路径部分缩短FullName:

foreach (ZipArchiveEntry entry in result)
{
    var newName = entry.FullName.Substring(root.Length);
    string path = Path.Combine(extractPath, newName);

    if (!Directory.Exists(path))
        Directory.CreateDirectory(Path.GetDirectoryName(path));

    entry.ExtractToFile(path);
}
相关问题