Reputation: 417
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
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
Upvotes: 3
Views: 1824
Reputation: 7105
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()
Upvotes: 1
Reputation: 638
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("/"));
}
Upvotes: 1