How can I delete a directory in a Zip file using .NET?

邮差的信 提交于 2019-11-29 11:32:36

First tought. Don't loop with foreach while removing elements from the collection.
I will try in this way

for(int x = zip.Count -1; x >= 0; x--) 
{ 
    ZipEntry e = zip[x];
    if(e.FileName.Substring(0, 9) == "FolderName/") 
        zip.RemoveEntry(e.FileName);                           
} 

However, looking at the methods of the ZipFile class, I noticed the method: SelectEntries that return a ICollection. So I think it's possible to do:
EDIT: Use overloaded version SelectEntries(string,string)

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

removing the loop on all entries in the zipfile

Here's a simple way to do this:

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

Documentation here http://dotnetzip.herobo.com/DNZHelp/Index.html

In order to delete the directory and all nested child entries, I used

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);
}

Note that the path must end with a slash, like dir/subdir/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!