how to count the number of files in zipfile in C #

advertisements

Please tell me how to count the number of files in ZIP file.

I need a C# code to do this job in visual studio. Tried many codes when I Googled but getting an error saying:

The namespace or assembly is not found for ZIPENTRY/ZIPFILE.

Can anyone tell me what i should include/anything need to be installed/provide me any code to count the number of files?


As MSDN puts it (.Net 4.5) you can use ZipArchive and ZipFile classes:

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

the classes being both in System.IO.Compression namespace are in different assemblies System.IO.Compression and System.IO.Compression.FileSystem though.

so you may add references to System.IO.Compression and System.IO.Compression.FileSystem assemblies to your project and try something like this:

...
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;
    }
  }

Another possibility is to use DotNetZip library, see:

Count number of files in a Zip File with c#