![](/img/trans.png)
[英]in C# .net framework 2.0 how can i unzip a .zip file to a specified directory and have it wait untill it is done before moveing on
[英]How can I delete a directory in a Zip file using .NET?
如何刪除 .zip 中的目錄及其中的所有文件(最好使用 DotNetZip)?
現在我正在瀏覽 zip 中的所有文件,但它不起作用:
foreach (ZipEntry e in zip)
{
//If the file is in the directory I want to delete
if(e.FileName.Substring(0, 9) == "FolderName/")
{
zip.RemoveEntry(e.FileName);
}
}
有沒有更好的方法,如果沒有,我將如何進行這項工作?
這是一個簡單的方法來做到這一點:
using (ZipFile zip = ZipFile.Read(@"C:\path\to\MyZipFile.zip"))
{
zip.RemoveSelectedEntries("foldername/*"); // Delete folder and its contents
zip.Save();
}
第一次嘗試。 從集合中刪除元素時不要使用 foreach 循環。
我會以這種方式嘗試
for(int x = zip.Count -1; x >= 0; x--)
{
ZipEntry e = zip[x];
if(e.FileName.Substring(0, 9) == "FolderName/")
zip.RemoveEntry(e.FileName);
}
但是,查看 ZipFile 類的方法時,我注意到方法:返回 ICollection 的 SelectEntries。 所以我認為可以這樣做:
編輯:使用重載版本 SelectEntries(string,string)
var selection = zip1.SelectEntries("*.*", "FolderName");
for(x = selection.Count - 1; x >= 0; x--)
{
ZipEntry e = selection[x];
zip.RemoveEntry(e.FileName);
}
刪除 zipfile 中所有條目的循環
您可以按如下方式實現
using (ZipArchive zip = ZipFile.Open(@"C:\path\to\MyZipFile.zip", ZipArchiveMode.Update))
{
zip.Entries.Where(x => x.FullName.Contains("Foldername")).ToList()
.ForEach(y =>
{
zip.GetEntry(y.FullName).Delete();
});
}
注意:如果文件夾中的所有文件都被刪除,則該文件夾將被自動刪除。
為了刪除目錄和所有嵌套的子條目,我使用了
var sel = (from x in zip.Entries where x.FileName.StartsWith(path, StringComparison.OrdinalIgnoreCase) select x.FileName).ToList();
foreach (var fn in sel)
{
zip.RemoveEntry(fn);
}
請注意,路徑必須以斜杠結尾,例如dir/subdir/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.