Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 452
eMizo Avatar asked Sep 10 '13 08:09

eMizo


People also ask

Can you extract multiple folders at once?

WinZip can quickly unzip multiple files through its drag and drop interface. You can select multiple WinZip files, right click, and drag them to a folder to unzip them all with one operation. To unzip multiple Zip files without drag and drop: From an open folder window, highlight the WinZip files you want to Extract.

How do I zip all files and subdirectories in Linux?

Syntax : $zip –m filename.zip file.txt 4. -r Option: To zip a directory recursively, use the -r option with the zip command and it will recursively zips the files in a directory. This option helps you to zip all the files present in the specified directory.


1 Answers

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); 
like image 158
Dmitrii Dovgopolyi Avatar answered Sep 22 '22 12:09

Dmitrii Dovgopolyi