.NET4.5 Compression Library Path Handling

In .NET4.5 Microsoft added built-in ZIP support to the compression library (System.IO.Compression).

The paths of entries added to a ZipArchive are not checked for conformance with the PKWARE specification by the library. It is worth mentioning since I didn’t find much about it on the internet.

The PKWARE zip specification states:

4.4.17 file name: (Variable)

4.4.17.1 The name of the file, with optional relative path. The path stored MUST not contain a drive or device letter, or a leading slash. All slashes MUST be forward slashes ‘/’ as opposed to backwards slashes ‘\’ for compatibility with Amiga and UNIX file systems etc. If input came from standard input, there is no file name field.

On windows the default directory separator is the forward slash ‘/’. So it is worth checking and converting paths if necessary before adding a zip entry. Unix zip programs (such as unzip) will show a warning and attempt to convert paths but others may fail.

So when writing zip archive construction code in C# to ensure cross platform compatibility, do something like:

string entryName = "C:\\Foo\\Bar.txt";

if (Path.DirectorySeparatorChar == '\\')
    entryName = entryName.Replace('\\', '/');

The first line ensures that the replacement only happens on systems which use a backslash as the default directory separator character. Note that this assumes that multiple consecutive path characters have already been sanitised.

Published by

oughton

A software / web applications developer, living in Hamilton and currently studying at Waikato University.

Leave a Reply

Your email address will not be published. Required fields are marked *