c# - 在 C# 中解压缩子目录和文件

标签 c# .net zip compression

我正在尝试在我目前正在从事的项目中实现解压缩功能,但问题是我在许可方面有一些限制,我需要远离 GPL 类许可证,因为该项目是闭源的。

所以这意味着我不能再使用 SharpZipLib.. 所以我转向了 .Net 库 目前我正在尝试使用 ZipArchive 库。

问题是它不会提取目录/子目录,所以如果我有 blabla.zip 里面的file.txt和/folder/file2.txt会全部解压到file.txt和file2.txt,所以忽略子目录。

我正在使用 MSDN 网站上的示例。 看起来像:

using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
  foreach (ZipArchiveEntry entry in archive.Entries)
  {
    entry.ExtractToFile(Path.Combine(extractPath, entry.FullName));
  } 
}

知道如何解决这个问题吗?

最佳答案

如果您的存档如下所示:

archive.zip
  file.txt
  someFolder
    file2.txt

然后 file2.txt 的 entry.FullNamesomeFolder/file2.txt 所以如果文件夹存在,即使您的代码也能正常工作。所以你可以创建它。

foreach (ZipArchiveEntry entry in archive.Entries)
{
    string fullPath = Path.Combine(extractPath, entry.FullName);
    if (String.IsNullOrEmpty(entry.Name))
    {
        Directory.CreateDirectory(fullPath);
    }
    else
    {
        if (!entry.Name.Equals("please dont extract me.txt"))
        {
            entry.ExtractToFile(fullPath);
        }
    }
}

或者如果你需要提取所有存档,你最好使用静态ZipFile方法

ZipFile.ExtractToDirectory(zipPath, extractPath); 

关于c# - 在 C# 中解压缩子目录和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18714153/

相关文章:

c# - 模拟网络服务调用......有时

python - python 3.2.3 中的 Zip 函数无法正常工作

c# - Ninject:实现 WithConstructorArgument(string name, Func<IContext,object> callback)

c# - 知道文件被访问 IIS

当有 CR :CrystalReportViewer 时,C# 断点不命中

c# - CSLA getproperty、setproperty和一般getters和setters的区别

c# - 需要在没有 UAC 弹出窗口的情况下提升权限

asp.net - 如何更改 WebClient 中的 UrlReferrer

Rubyzip 与 native 操作系统压缩

Bash - 压缩后丢失新行字符