1

I am trying to get all the file names that are located in the top level of a zip file and not anything in subdirectories.

The code I'm currently using is

            using System.IO.Compression.ZipFile;

            using (var zip = ZipFile.OpenRead(pathToZip))
            {
              foreach (var e in zip.Entries)
              {
                  var filename = e.Name;
              }
            }

But this code gets all the files in the zip. Any help is much apricated.

Thanks

Christoff
  • 45
  • 4
  • 5
    You should be able to use [`FullName`](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.fullname?view=net-5.0) for this - _"The FullName property contains the relative path, **including the subdirectory hierarchy**, of an entry in a zip archive."_ - presumably if there's no hierarchy, then it's a top-level file. – stuartd May 04 '21 at 13:57
  • 1
    https://stackoverflow.com/questions/40223451/how-to-tell-if-a-ziparchiveentry-is-directory – geothachankary May 04 '21 at 14:01

1 Answers1

4

This code will extract only files that are not contained in a directory:

using (var zip = ZipFile.OpenRead(pathToZip))
{
    foreach (var e in zip.Entries.Where(e => !e.FullName.Contains("/")))
    {
        {
            var filename = e.Name;
            Console.WriteLine(filename);
        }
    }
}
stuartd
  • 70,509
  • 14
  • 132
  • 163
  • 1
    you can also check if Name is not IsNullOrWhiteSpace because in this case name is empty string – Emil Jul 10 '23 at 16:36