【问题标题】:Extract a zipped file only (without the folder)仅提取压缩文件(没有文件夹)
【发布时间】:2012-08-24 10:50:26
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# sharpziplib


    【解决方案1】:

    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)
    

    删除文件夹。

    【讨论】:

      【解决方案2】:

      假设您知道这是 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 的名称,复杂性相应增加。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        • 2020-08-13
        • 2010-12-14
        • 2016-01-10
        • 2012-06-19
        相关资源
        最近更新 更多