Working with Zip Files in .NET

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 + "test.zip";
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 text.zip 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 + "test.zip";
string ExtractionPath = @"C:\unzip";
  using (ZipArchiveZArchive zarchive = ZipFile.OpenRead(ZipFilePath))
  {
    foreach (ZipArchiveEntry zaEntry in zarchive.Entries)
    {
      zaEntry.ExtractToFile(Path.Combine(ExtractionPath,zaEntry.FullName));
    }
  }
}

Now if you run the above code, the zip file created above called test.zip 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.

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 http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One Comment to “Working with Zip Files in .NET”

Comments are closed.