praveen
praveen

Reputation: 111

how to count number of files in zipfile in c#

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?

Upvotes: 7

Views: 11518

Answers (4)

Vineet Agarwal
Vineet Agarwal

Reputation: 59

Use below:

using var zip = new ZipArchive(stream, ZipArchiveMode.Read);
var totalFiles = zip.Entries.Where(x=>x.Length>0).Count()

Folder do not have any Length

Upvotes: 2

adityaswami89
adityaswami89

Reputation: 583

You can try something like this, using DotNetZip.

using DotNetZip;

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

I found this solution here.

Upvotes: 1

Boris Maslennikov
Boris Maslennikov

Reputation: 351

You have to add references System.IO.Compression and System.IO.Compression.FileSystem to your project

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

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

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#

Upvotes: 6

Related Questions