![](/img/trans.png)
[英]How to extract just the specific directory from a zip archive in C# .NET 4.5?
[英]C# - extract specific directory from ZIP, preserving folder structure
我有一個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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.