Looping files in subdirectories of a ZIP archive

Suppose I have a zip file containing 10 text files. Easily 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 in a subdirectory:

 zip/subdirectory/file1.txt 

In this case, the above code only displays the subdirectory folder ("subdirectory"), unlike all text files in this folder.

Is there an easy way to iterate over files in a subdirectory?

+4
source share
2 answers

I played your program. When I iterate over the zip archive the way you do it, I get a list of all the files in the full directory structure of the archive. This way you don't need recursion, just repeat as you are doing now.

I understand your confusion as the API does not distinguish between files and folders. The following is the extension method:

 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 } } } 
+7
source

I can not 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

+2
source

Source: https://habr.com/ru/post/1490672/


All Articles