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

2019-06-03 15:17发布

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

2条回答
我只想做你的唯一
2楼-- · 2019-06-03 15:55

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.

查看更多
迷人小祖宗
3楼-- · 2019-06-03 16:13

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.

查看更多
登录 后发表回答