eMizo
eMizo

Reputation: 269

Unzipping subdirectories and files in C#

I am trying to implement an unzipping feature in a project that I am currently working on, but the problem is that I have some limitations when it comes to licening and I am required to stay away from GPL alike licenses, because the project is closed sourced.

So that means that I can no longer use SharpZipLib.. so I moved to .Net libraries Currently I am trying to work with the ZipArchive library.

The problem is that it does not extract for directories/subdirectories, so if I have blabla.zip that has file.txt inside and /folder/file2.txt the whole thing will be extracted to file.txt and file2.txt, so it ignores the subdirectory.

I am using the example from MSDN website. which looks something like:

using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
  foreach (ZipArchiveEntry entry in archive.Entries)
  {
    entry.ExtractToFile(Path.Combine(extractPath, entry.FullName));
  } 
}

Any idea how to solve this?

Upvotes: 7

Views: 8323

Answers (1)

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

if your archive looks like this:

archive.zip
  file.txt
  someFolder
    file2.txt

then entry.FullName for file2.txt is someFolder/file2.txt so even your code will work normaly if the folder exists. So you can create it.

foreach (ZipArchiveEntry entry in archive.Entries)
{
    string fullPath = Path.Combine(extractPath, entry.FullName);
    if (String.IsNullOrEmpty(entry.Name))
    {
        Directory.CreateDirectory(fullPath);
    }
    else
    {
        if (!entry.Name.Equals("please dont extract me.txt"))
        {
            entry.ExtractToFile(fullPath);
        }
    }
}

or you should better use static ZipFile method if you need to extract all the archive

ZipFile.ExtractToDirectory(zipPath, extractPath); 

Upvotes: 15

Related Questions