Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DotNetZip: How to extract files, but ignoring the path in the zipfile?

Tags:

c#

zip

dotnetzip

Trying to extract files to a given folder ignoring the path in the zipfile but there doesn't seem to be a way.

This seems a fairly basic requirement given all the other good stuff implemented in there.

What am i missing ?

code is -

using (Ionic.Zip.ZipFile zf = Ionic.Zip.ZipFile.Read(zipPath))
{
    zf.ExtractAll(appPath);
}
like image 374
Kumar Avatar asked Mar 09 '10 00:03

Kumar


2 Answers

You can use the overload that takes a stream as a parameter. In this way you have full control of path where the files will be extracted to.

Example:

using (ZipFile zip = new ZipFile(ZipPath))
{
     foreach (ZipEntry e in zip)
     {
        string newPath = Path.Combine(FolderToExtractTo, e.FileName);

        if (e.IsDirectory)
        {
           Directory.CreateDirectory(newPath);
        }
        else
        {
          using (FileStream stream = new FileStream(newPath, FileMode.Create))
             e.Extract(stream);
        }
     }
}
like image 158
Chopain Avatar answered Oct 17 '22 14:10

Chopain


While you can't specify it for a specific call to Extract() or ExtractAll(), the ZipFile class has a FlattenFoldersOnExtract field. When set to true, it flattens all the extracted files into one folder:

var flattenFoldersOnExtract = zip.FlattenFoldersOnExtract;
zip.FlattenFoldersOnExtract = true;
zip.ExtractAll();
zip.FlattenFoldersOnExtract = flattenFoldersOnExtract;
like image 34
Andrew Timson Avatar answered Oct 17 '22 14:10

Andrew Timson