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

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

我很肯定那是因为我在 Path.Combine() 中使用 entry.Name 而不是 entry.FullName,但是如果我要使用 FullName,我会在根目录 dirA 的路径中尝试不提取。 所以我在这里碰壁了,我能想到的唯一解决方案是使用以下方法提取整个 zip:

ZipFile.ExtractToDirectory(archivePath, extractPath);

...然后将子文件夹从 dirA 移动到不同的位置并删除 dirA。这似乎不是最幸运的想法。

非常感谢任何帮助。

最佳答案

您可以将 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);
}

关于C# - 从 ZIP 中提取特定目录,保留文件夹结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36350199/

相关文章:

c# - 获取一组矩形的轮廓

c# - 任务 - 属性分配

c# - 如何将 dropDownlist 映射到 C# 中的枚举?

c# - WPF ListBox 按钮选择的项目

python - Maya Python 创建和使用压缩包?

c# - LINQ 和 Array.Copy

c# - 登录 session 未使用 WebRequest/Response 转移到新网页?

c# - 传递凭据适用于 WebRequest,但不适用于 HttpClient

java - 监控压缩文件

php - 如何使用 PHP 压缩整个文件夹