C#:仅提取压缩文件(不带文件夹)

时间:2012-08-24 10:50:27

标签: c# sharpziplib

使用SharpZip lib,我可以轻松地从zip存档中提取文件:

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

但是,这会将未压缩的文件夹放在输出目录中。 假设bla.zip中有一个我想要的foo.txt文件。是否有一种简单的方法来提取它并将其放在输出目录中(没有文件夹)?

2 个答案:

答案 0 :(得分:2)

FastZip似乎没有提供更改文件夹的方法,只有the "manual" way of doing supports this

如果你看看他们的例子:

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();
        }
    }
}

正如他们所指出的那样,而不是写作:

String entryFileName = zipEntry.Name;

你可以写:

String entryFileName = Path.GetFileName(entryFileName)

删除文件夹。

答案 1 :(得分:1)

假设您知道这是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-entry的名称后,复杂性也随之提高。