How to Extract Zip File in C#

In this how to tutorial, we’ll show you how to extract Zip file in C# code. You can use C# to Unzip an archive in your applications. This code supports multiple zip or archive file formats like GZip, RAR, TAR, 7Zip and more.

Steps to Extract Zip File in C#

  1. Install Aspose.Zip for .NET package from NuGet.org
  2. Include Aspose.Zip namespace in the code
  3. Use SetLicense method to setup license of Aspose.Zip API
  4. Load input Zip file into a FileStream object
  5. Create a new Archive object from the file stream
  6. Get count of files in the archive and loop through the archive entries
  7. Extract each archive entry and save the file to the disk

Each entry in the archive contains not only file, but also the name of the file. We have used the Name property to get the file name and then extracted file with the same name.

Code to Extract Zip File in C#

using System;
using System.IO;
using System.Text;
//Add reference to Aspose.Zip for .NET API
//Use following namespace to extract zip file
using Aspose.Zip;
namespace ExtractZipFile
{
class Program
{
static void Main(string[] args)
{
//Set Aspose license before extracting Zip file
//using Aspose.Zip for .NET
Aspose.Zip.License AsposeZipLicense = new Aspose.Zip.License();
AsposeZipLicense.SetLicense(@"c:\asposelicense\license.lic");
//Open file from disk using a file stream
FileStream ZipFileToBeExtracted = File.Open("ZipFileToBeExtracted.zip", FileMode.Open);
//Load Zip file stream to Archive object
Archive ZipArchiveToExtract = new Archive(ZipFileToBeExtracted);
//Get number of files
int NumberOfFileInArchive = ZipArchiveToExtract.Entries.Count;
//Loop through the archive for each file
for(int FileCounter =0; FileCounter < NumberOfFileInArchive; FileCounter++)
{
//Get each zip archive entry and extract the file
ArchiveEntry ArchiveFileEntry = ZipArchiveToExtract.Entries[FileCounter];
string NameOfFileInZipEntry = ArchiveFileEntry.Name;
ArchiveFileEntry.Extract(NameOfFileInZipEntry);
}
}
}
}

In the above code, we have used FileStream to load the Zip archive and then saved the extracted output files on the disk. You can also use this code in C# to unzip file in memory. This can be helpful when you need those files further in the code or application and do not want to save to disk. Using this code, you can easily and quickly create your own C# Zip extractor in your applications or as an independent utility.

 English