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

回眸只為那壹抹淺笑 提交于 2019-12-08 05:08:14

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12107966/c-extract-a-zipped-file-only-without-the-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!