我有一个 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/