【问题标题】:how to count number of files in zipfile in c#如何在c#中计算zipfile中的文件数
【发布时间】:2013-08-28 05:17:53
【问题描述】:

请告诉我如何计算 ZIP 文件中的文件数。

我需要一个 C# 代码来在 Visual Studio 中完成这项工作。谷歌搜索时尝试了许多代码,但收到错误消息:

找不到 ZIPENTRY/ZIPFILE 的命名空间或程序集。

谁能告诉我我应该包含什么/需要安装什么/提供任何代码来计算文件数量?

【问题讨论】:

标签: c# zip


【解决方案1】:

正如 MSDN 所说(.Net 4.5),您可以使用 ZipArchiveZipFile 类:

http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.aspx http://msdn.microsoft.com/en-us/library/system.io.compression.zipfile.aspx

同时在 System.IO.Compression 命名空间中的类位于不同的程序集中 System.IO.CompressionSystem.IO.Compression.FileSystem

因此您可以在项目中添加对 System.IO.CompressionSystem.IO.Compression.FileSystem 程序集的引用,然后尝试以下操作:

...
using System.IO.Compression; 
...


  // Number of files within zip archive
  public static int ZipFileCount(String zipFileName) {
    using (ZipArchive archive = ZipFile.Open(zipFileName, ZipArchiveMode.Read)) {
      int count = 0;

      // We count only named (i.e. that are with files) entries
      foreach (var entry in archive.Entries)
        if (!String.IsNullOrEmpty(entry.Name))
          count += 1;

      return count;
    }
  }

另一种可能是使用 DotNetZip 库,请参阅:

Count number of files in a Zip File with c#

【讨论】:

    【解决方案2】:

    您必须将引用 System.IO.CompressionSystem.IO.Compression.FileSystem 添加到您的项目

    using (var archive = System.IO.Compression.ZipFile.Open(filePath, ZipArchiveMode.Read))
    {
        var count = archive.Entries.Count(x => !string.IsNullOrWhiteSpace(x.Name));
    }
    

    【讨论】:

      【解决方案3】:

      你可以尝试这样的事情,使用DotNetZip

      using DotNetZip;
      
      int count;
      using (ZipFile zip = ZipFile.Read(path))
          count = zip.Count;
      

      我找到了这个解决方案here

      【讨论】:

      • 对不起,但是根据 MSDN msdn.microsoft.com/en-us/library/… ZipFile 是一个静态类,没有 ZipFile zip = ... 是可能的
      • 您是从this 答案中获得此代码的吗?如果是这样,请指出(并添加关于“DotNetZip”的部分,这至少会使您的代码有效,关于@DmitryBychenko 的评论)
      猜你喜欢
      • 2011-03-05
      • 1970-01-01
      • 2022-01-22
      • 2016-04-17
      • 2013-05-30
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多