Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

dotnetzip

How would I delete a directory in a .zip and all the files in it (preferably using DotNetZip)?

Right now I'm running through all the files in the zip, but it doesn't work:

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

Is there a better way, if not, how would I make this work?

like image 617
Chris Avatar asked Dec 01 '22 23:12

Chris


2 Answers

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

like image 197
kosinix Avatar answered Dec 24 '22 02:12

kosinix


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

like image 24
Steve Avatar answered Dec 24 '22 00:12

Steve