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 + "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.

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.