如何使用.NET删除Zip文件中的目录?

如何删除.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); } } 

有没有更好的方法,如果没有,我将如何使这项工作?

第一次尝试。 从集合中删除元素时,不要使用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(字符串,字符串)

 var selection = zip1.SelectEntries("*.*", "FolderName"); for(x = selection.Count - 1; x >= 0; x--) { ZipEntry e = selection[x]; zip.RemoveEntry(e.FileName); } 

删除zipfile中所有条目的循环

这是一个简单的方法:

 using (ZipFile zip = ZipFile.Read(@"C:\path\to\MyZipFile.zip")) { zip.RemoveSelectedEntries("foldername/*"); // Delete folder and its contents zip.Save(); } 

文档http://dotnetzip.herobo.com/DNZHelp/Index.html

为了删除目录和所有嵌套的子条目,我使用了

 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/