Zip Archive Class in .NET 4.5

In .NET 4.5, the System.IO.Compression namespace contains the following new classes for compressing and decompressing the streams:

1- ZipArchive which represents a Zip archive.

2- ZipArchiveEntry which represents an entry in the zip archive.

The ExtractToDirectory and CreateFromDirectory methods of ZipArchive class can be used to handle the following most used scenarios:

Scenario 1 – Unzipping: Use ExtractToDirectory method to extract all the contents of a zip archive to the specified directory

Scenario 2 – Zipping: the contents: Use CreateFromDirectory to take the contents of the directory and to zip it’s content to a zip file

Example 1. ZipArchive.CreateFromDirectory(@”docs\attach”, “attachment.zip”);

Example 2. ZipArchive.ExtractToDirectory(“Photos.zip”, @”photos\January2012″);

What is ZipArchiveEntry?

ZipArchive represents a zip archive, which is a collection of entries, and ZipArchiveEntry represents an archived file entry.
A ZipArchive class (representing a zip file ) can have one or more ZipArchiveEntry class (representing normal files like text file, doc file, pdf file etc)

The following example extracts only the text files from an archive:

using (var archive = new ZipArchive(“data.zip”))
{

foreach (var entry in archive.Entries)
{

if (entry.FullName.EndsWith(“.txt”, StringComparison.OrdinalIgnoreCase))
{

entry.ExtractToFile(Path.Combine(directory, entry.FullName));

}

}

}

Copyright © All Rights Reserved - C# Learners