简体   繁体   中英

Get number of folders in root of ZipFile

I'm trying to check if my zip is valid .

The zip file looks like this (only one root folder with content):

zip-root
`-- folder1
    |-- folder1
    |-- folder2
    |-- folder3
    |-- folder4
    `-- folder5

The structure of the zip file is considered invalid if

  • root of zip contains more than one folder

I tried the following:

using (ZipArchive archive = ZipFile.OpenRead(ZipFilePath))
{
    rootArchiveFolder = archive.Entries.Count();        
}

but this returns the count of all folders, whereas I'm only interested in the root-folder-count

The problem is that the entries list is flat. But with this filter, you should be able to get the root-folder-count.

int foldersCount;
using (var zip = ZipFile.OpenRead(file))
{
    foldersCount = zip.Entries.Count(e => e.FullName.Split('/').Length == 3 && e.FullName.EndsWith("/"));
}

Folder is recognised with its FullName ending with slash ( / ). So, in your case, you can get list of folders inside the root of archive like this:

using (ZipArchive archive = ZipFile.OpenRead(ZipFilePath)
{
    var listOfZipFolders = archive.Entries.Where(x => x.FullName.EndsWith("/")).ToList();
    int foldersCount = archive.Entries.Count(x => x.FullName.EndsWith("/"));
}

or, LINQless version:

using (ZipArchive archive = ZipFile.OpenRead(ZipFilePath))
{
    List<ZipArchiveEntry> listOfZipFolders = new List<ZipArchiveEntry>();
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        if (entry.FullName.EndsWith("/"))
            listOfZipFolders.Add(entry);
    }
    int foldersCount = listOfZipFolders.Count;
}

EDIT : previous code examples work only with empty folders.

this will find a list of root folders (empty, not empty or having subfolders)

var folders = archive.Entries
    .Where
        (x => x.FullName.Split('/').Length > 1 || 
           x.FullName.EndsWith("/")
        )
    .Select(f => f.FullName.Split('/')`[0])
    .Distinct()
    .ToList();

var foldersCount = archive.Entries
    .Where
        (x => x.FullName.Split('/').Length > 1 || 
           x.FullName.EndsWith("/")
        )
    .Select(f => f.FullName.Split('/')`[0])
    .Distinct()
    .Count()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM