ZIP Functionality in .NET framework 4.5

The ability to compress multiple files into a single, smaller file is useful for

  • Reducing storage and data bandwidth requirements
  • Creating backups.
  • Archiving multiple versions of files
  • Detecting file modifications.

However the commonly available in .ZIP file formats are not easy to use with Microsoft.NET. Hence Microsoft has introduced this new feature in 4.5.

Following are the new namespaces required to use this functionality

  • System.IO.Compression.FileSystem
  • System.IO.Compression

The following example shows how we can create and extract a zip file. It compresses the contents of the folder into a zip archive, and then extracts that content to a new folder.

Archiving from a Directory

string filesToBeArchived = @"D:\Test";

string zipFilePath = @"D:\Zipped.zip";

string extractFilePath = @"D:\extract";

 

//create the zip file

ZipFile.CreateFromDirectory(filesToBeArchived, zipFilePath);

 

//extract the zip file

ZipFile.ExtractToDirectory(zipFilePath, extractFilePath);

Archiving a File

string fileToBeArchived = @"D:\Test.txt";

string zipFilePath = @"D:\Zipped.zip";

string extractFilePath = @"D:\extract";

using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Update))

{

    //create the zip file

    archive. CreateEntryFromFile(fileToBeArchived, “NewFile.txt”);

    //extract the zip file

    archive.ExtractToDirectory(extractFilePath);

}

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now