Question

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)?

Was it helpful?

Solution

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.

OTHER TIPS

Assuming you know this is the only file (not folder) in the zip:

using(ZipFile zip = new ZipFile(zipStm))
{
  foreach(ZipEntry ze in zip)
    if(ze.IsFile)//must be our foo.txt
    {
      using(var fs = new FileStream(@"C:/Unzips/foo.txt", FileMode.OpenOrCreate, FileAccess.Write))
        zip.GetInputStream(ze).CopyTo(fs);
      break;
    }  
}

If you need to handle other possibilities, or e.g. getting the name of the zip-entry, the complexity rises accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top