【问题标题】:C# - extract specific directory from ZIP, preserving folder structureC# - 从 ZIP 中提取特定目录,保留文件夹结构
【发布时间】:2016-07-20 21:33:43
【问题描述】:

我有一个 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。这似乎不是最幸运的想法。

非常感谢任何帮助。

【问题讨论】:

标签: c# .net zip compression


【解决方案1】:

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

【讨论】:

  • 为什么,这是一个很好的解决方法,现在看起来非常明显!谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-01-15
  • 2011-06-22
  • 2014-08-05
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多