Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over files in subdirectories of a ZIP archive

Tags:

c#

.net

zip

Assume I have a zip file which contains 10 text files. It's easy to iterate over these text files using:

using (ZipArchive archive = ZipFile.OpenRead(zipIn))
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        Console.writeLine(entry)
    }
}

However, suppose the text files are within a subdirectory:

zip/subdirectory/file1.txt

In this case the above code only outputs the subdirectory folder ('subdirectory'), as opposed to all the text files within that folder.

Is there a simple way of looping over the files in the subdirectory also?

like image 984
FBryant87 Avatar asked Jul 10 '13 09:07

FBryant87


2 Answers

I have reproduced your program. When I iterate over a zip archive the way you do it, I get a list of all files in the full directory structure within the archive. So you do not need recursion, just iterate like you are doing now.

I understand your confusion since the API does not make a distinction between files and folders. Here is an extension method to help:

static class ZipArchiveEntryExtensions
{
    public static bool IsFolder(this ZipArchiveEntry entry)
    {
        return entry.FullName.EndsWith("/");
    }
} 

Then you can do:

using (var archive = ZipFile.OpenRead("bla.zip"))
{
    foreach (var s in archive.Entries)
    {
        if (s.IsFolder())
        {
            // do something special
        }

    }
 }
like image 74
Bas Avatar answered Sep 23 '22 23:09

Bas


I can't reproduce your problem. It works fine in my test case:

using (var archive = ZipFile.OpenRead(zipIn))
{
    foreach (var zipArchiveEntry in archive.Entries)
    {
        Console.WriteLine(zipArchiveEntry);
    }
}
Console.ReadLine();

Result:

enter image description here

like image 20
Herdo Avatar answered Sep 23 '22 23:09

Herdo