使用 SharpZipLib 我可以很容易从 zip 存档提取文件:
FastZip fz = new FastZip();
string path = "C:/bla.zip";
fz.ExtractZip(bla,"C:/Unzips/",".*"); 然而这也同时将未压缩的文件夹放到了输出目录中。假设我想要 bla.zip 内的 foo.txt 文件。有没有简单的方法,只提取这个文件,并将其放置在输出目录中 (而不包含文件夹) ?
FastZip 似乎不提供方法来改变文件夹,但“手动”方式支持这样做,如果你看看他们的例子:
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; // 忽略目录文件夹
            String entryFileName = zipEntry.Name;
            // 从条目中移除文件夹:
            // entryFileName = Path.GetFileName(entryFileName);
            byte[] buffer = new byte[4096];     // 4K 是最优的
            Stream zipStream = zf.GetInputStream(zipEntry);
            // 操作所需的输出文件名。
            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();
        }
    }
} 需要注意的是,不要这样写:
String entryFileName = zipEntry.Name; 你可以这样写
String entryFileName = Path.GetFileName(entryFileName) 
移除文件夹。
前提假设是你知道这是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;
    }  
} 如果你需要处理其他的可能性,例如得到的 zip 文件项的名称,复杂性相应上升。
 
                    

