C#: Extract a zipped file only (without the folder)

FBryant87 picture FBryant87 · Aug 24, 2012 · Viewed 8k times · Source

With the SharpZip lib I can easily extract a file from a zip archive:

FastZip fz = new FastZip();
string path = "C:/bla.zip";
fz.ExtractZip(bla,"C:/Unzips/",".*");

However this puts the uncompressed folder in the output directory. Suppose there is a foo.txt file within bla.zip which I want. Is there an easy way to just extract that and place it in the output directory (without the folder)?

Answer

Uwe Keim picture Uwe Keim · Aug 24, 2012

The FastZip does not seem to provide a way to change folders, but the "manual" way of doing supports this.

If you take a look at their example:

public void ExtractZipFile(string archiveFilenameIn, string outFolder) {
    ZipFile zf = null;
    try {
        FileStream fs = File.OpenRead(archiveFilenameIn);
        zf = new ZipFile(fs);

        foreach (ZipEntry zipEntry in zf) {
            if (!zipEntry.IsFile) continue; // Ignore directories

            String entryFileName = zipEntry.Name;
            // to remove the folder from the entry:
            // entryFileName = Path.GetFileName(entryFileName);

            byte[] buffer = new byte[4096];     // 4K is optimum
            Stream zipStream = zf.GetInputStream(zipEntry);

            // Manipulate the output filename here as desired.
            String fullZipToPath = Path.Combine(outFolder, entryFileName);
            string directoryName = Path.GetDirectoryName(fullZipToPath);
            if (directoryName.Length > 0)
                Directory.CreateDirectory(directoryName);

            using (FileStream streamWriter = File.Create(fullZipToPath)) {
                StreamUtils.Copy(zipStream, streamWriter, buffer);
            }
        }
    } finally {
        if (zf != null) {
            zf.IsStreamOwner = true;stream
            zf.Close();
        }
    }
}

As they note, instead of writing:

String entryFileName = zipEntry.Name;

you can write:

String entryFileName = Path.GetFileName(entryFileName)

to remove the folders.