Zip Archive Gets Native Support in .NET 4.5

With v4.5, zip archival handling comes natively to .NET. No longer do you have to rely on 3rd party components to create, manage and extract zip files, though most of them are free.

The types you require to manage zip archives reside in System.IO.Compression namespace, in the System.IO.Compression.dll assembly and those types are ZipArchive and ZipArchiveEntry. The first one represents the zip file as a single entity while the latter represents an individual file in that zip. Note that ZipArchive acts like a pass-through stream, which means you should have a backing store (storage stream) such as a file on the disk.

ZipArchive & ZipArchiveEntry

Creating a zip file and packaging one or more files into it is relatively straight-forward. The following code creates a new zip file,, containing a single content file CS Summary.ppt.

Code Snippet

You may provide a relative path in CreateEntry if you would like to keep files in hierarchical way in the archive. The following code iterates a zip file’s contents and gets few basic details about each file in it:

Code Snippet

Extracting a file from the zip archive is as easy as packaging one into the archive but just in opposite direction:

Code Snippet

If you notice the above code listings for reading and writing zip files, we are dealing with multiple stream objects, even to create/read a single archive and write/extract a single entry into/from that archive. To ease the whole thing, .NET 4.5 has few convenient types with which you can create and read zip files with fewer lines of code. Basically, these types add extension methods to ZipArchive and ZipArchiveEntry types. Note that you have to add reference to the System.IO.Compression.FileSystem.dll assembly. The following code creates a new zip with a single file in it:

Code Snippet

Of course, you can add as many files as you want to the archive by calling CreateEntryFromFile multiple times. As of this writing, this method doesn’t support adding an entire folder to the zip just by specifying the folder name for the first parameter (or by any other means).

Extracting a file from zip is as easy the following code which extracts the first available file in the archive (assuming it is not a folder) and saves it to the file system:

Code Snippet

MSDN Reference: System.IO.Compression Namespace

category: .NET, C#    

Comments are closed.