Search code examples
c#dotnetzip

Enumerate contents of specific folder DotNetZip, without child folders


Using Ionic.Zip

I wish to display the files or folders in a specific folder. I am using the SelectEntries method, but it unfortunately is filtering out the folders. Not what I was expecting using '*'.

ICollection<ZipEntry> selectEntries = _zipFile.SelectEntries("*",rootLocation)

If I follow an alternative approach:

IEnumerable<ZipEntry> selectEntries = _zipFile.Entries.Where(e => e.FileName.StartsWith(rootLocation))

I face two problems:

  1. I have to switch '/' for '\' potentially.
  2. I get all the subfolders.

Which is not desirable.

Anyone know why SelectEntries returns no folders, or am I misusing it?


Solution

  • I found a solution in my particular case. I think something about the way the Zipfile was constructed led to it appearing to have folders but none actually existed i.e. the following code yielded an empty list.

    _zipFile.Entries.Where(e=>e.IsDirectory).AsList();  // always empty!
    

    I used the following snippet to achieve what I needed. The regex is not as comprehensive as it should be but worked for all cases I needed.

    var conformedRootLocation = rootLocation.Replace('\\','/').TrimEnd('/') + "/";
    var pattern = string.Format(@"({0})([a-z|A-Z|.|_|0-9|\s]+)/?", conformedRootLocation);
    var regex = new Regex(pattern);
    return _zipFile.EntryFileNames.Select(e => regex.Match(e))
            .Where(match => match.Success)
            .Select(match => match.Groups[2].Value)
            .Distinct()
            .Select(f => new DirectoryResource
            {
                Name = f, IsDirectory = !Path.HasExtension(f)
            })
            .ToList();