Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Avoid Illegal Characters in Path error in ZipArchive files with .DS_Store data or unix files

0.00/5 (No votes)
7 Jul 2015 1  
If a Zip file has his origin in Linux or Mac. ZipArchive class can fail trying to return Entries Collection

Introduction

This Helps Class allows to obtain a Raw Collection of Entries from ZipArchive with no Path Checking.

Later, you can use selected valid entries to deflate or rename or whatever you want.

Background

ZipArchive has a public property called Entries as single access to all entries (filenames and directories) contained in a Zip file.

But, ZipArchive user internaly System.IO.Path.CheckInvalidPathChars agains all entries before return the entries collection.

When we are working against Mac or Linux created Zip files those entries can have ".DS_Store" o similar names not valid in windows for historical reasons.

In those cases. ZipArchive fails without alternatives.

Using the code

This simple extension, add a GetRawEntries() method to avoid this problem.

//
// Workaround Entries Collection in ZipArchive
// (C)2015 Ramon Ordiales
//

public static class ZipArchiveHelper
{
  private static FieldInfo _Entries;
  private static MethodInfo _EnsureDirRead;
  static ZipArchiveHelper()
  {
    _Entries= typeof(ZipArchive).GetField("_entries",BindingFlags.NonPublic|BindingFlags.Instance);
    _EnsureDirRead = typeof(ZipArchive).GetMethod("EnsureCentralDirectoryRead", BindingFlags.NonPublic | BindingFlags.Instance);
  }
  public static List<ZipArchiveEntry> GetRawEntries(this ZipArchive archive)
  {
     _EnsureDirRead.Invoke(archive, null);
     return (List<ZipArchiveEntry>)_Entries.GetValue(archive);
   }
}

 

Points of Interest

"Private Static FieldInfo _Entries" is a variable stored once at startup. So, there are no performance impact using this code.

All Zip Entries into ZipArchive exists before the "Entries" Call. It simply exposes all entries whit an extra Path checking (Just the checking we want avoid).

History

This problem is here for years, especially non-English developers and/or Linux/Mac native Zip Files. 

Update: Add "EnsureCentralDirectoryRead" before extract entries.

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here