This project is read-only.

Unzip ignoring path

Feb 9, 2010 at 4:03 PM

Is there a way to unzip a ZipEntry without using it's path short of unzipping to a stream that is writing to a file?


I'm unzipping files that sometimes have been zipped by others by zipping up a whole folder, which puts the folder entry in the zip.  I have no control over how they get created, but I'd like to control how I can extract the files.  Using the ZipEntry.Extract(outputPath) methods seem to always use the path as well as the file name.  Is the only way around this to use Extract(Stream)?

Feb 9, 2010 at 7:34 PM

Extracting to a FileStream is one way to do what you want. 

Another way is to strip the path from the FileName on the ZipEntry before extracting.  Like so:

using (var zip = ZipFile.Read(whatever))
  foreach (var entry in zip)
    entry.FileName = System.IO.Path.GetFileName(e.FileName);

Some explanation: Each ZipEntry knows how to extract itself to a file, with the filename given by the FileName property on the ZipEntry class. The code above simply sets the FileName property on each entry to the value of the FileName without any leading path. Then it calls Extract(), which will extract the entry into the current working directory. You can use the appropriate Extract() overload to extract into a directory of your choice. Because the code above does not call ZipFile.Save(), the changes made to the ZipEntry instances are not made permanent. If you were to re-open the same ZipFile, the paths would again be present on all the ZipEntry instances.


Feb 9, 2010 at 9:07 PM

Ah, that does make sense.  I didn't realize they were read/write.  I guess I was looking at it from more of a command line or unilateral point of view where I might say zip.IgnorePaths or something before extracting anything.


Anyhow, this works!