Working with Zip Files in .NET

By | October 19, 2013

Zipping and Unzipping in a Client Application or a Website is very common requirement. Until the latest .NET version, there is no API that fully supports these things. We would have relied on J# specific JAVA APIs or there are superior 3rd party APIs available which could have done the trick.

.NET 4.5 gives an edge on handling normal Zip files using System.IO.Compression.FileSystem assembly. Let us create a Zip file using .NET.

string ZipPath= @"C:\";
string ZipFilePath = ZipPath + "";
string File1 = "Abhishek.txt";
string File2 = "Abhijit.txt";
string FileToZip1 = ZipPath + File1;
string FileToZip2 = ZipPath + File2;
 using (FileStreamZipToOpen = new FileStream(ZipFilePath, FileMode.CreateNew))
   using (ZipArchiveZArchive = new ZipArchive(ZipToOpen,ZipArchiveMode.Create))
     ZArchive.CreateEntryFromFile(FileToZip1, File1);
     ZArchive.CreateEntryFromFile(FileToZip2, File2);

Here in the code above, the is created on the File system which contains two files, “Abhishek.txt and Abhijit.txt”.

You can specify any file types to be included on the Zip archive.

Now to extract a Zipped archive let us take a look on the code :

string ZipPath = @"C:\";
string ZipFilePath = ZipPath + "";
string ExtractionPath = @"C:\unzip";
  using (ZipArchiveZArchive zarchive = ZipFile.OpenRead(ZipFilePath))
    foreach (ZipArchiveEntry zaEntry in zarchive.Entries)

Now if you run the above code, the zip file created above called will be unzipped on an unzip folder with all the content.

You can use ZipArchiveEntry to get additional info of the compressed file inside the zip archive, not just the FullName. You can find actual file size from Length, Actual file size inside the archive using CompressedLength or even get LastWriteTime etc. You can even delete a file inside an archive using ZipArchiveEntry.Delete method.

So finally, you could rely on managed environment to handle zip files.

Hope this post helps.

Thank you for reading.

Author: Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One thought on “Working with Zip Files in .NET

  1. Pingback: OS X Mavericks Is Free - The Daily Six Pack: October 24, 2013

Comments are closed.