USING IRONZIP

How to Open Zip File in C#

ZIP is an archive entry file system format that supports lossless data compression. A ZIP file may contain one or more files or directories that may have been compressed. The ZIP file format permits several compression algorithms, though DEFLATE is the most common. ZIP format was then quickly supported by many software utilities. Top OS providers have included ZIP archive support for a long time. Microsoft has included ZIP file support from Windows 98 and the rest followed suit.

In this blog, we are going to explore a modern, easy, and efficient way to open ZIP archive files or extracted files using IronZIP. We are going to learn about ZIP files in general and its advantages. Then we will see options available in the system namespace for working with ZIP file format. Then we will explore step-by-step instructions to open the ZIP file, extract ZIP file to a temp folder, create a new ZIP file, and add files to existing ZIP files.

Advantages of using ZIP files in software applications

  1. Compression: This technique reduces the size of the archived files/folder using various compression algorithms like Implode, Deflate, Deflate64, bzip2, LZMA, WavPack, PPMd, etc.
  2. Reduced Transfer Time: Smaller file sizes mean faster transfer times, especially when sending files over the Internet. This is particularly advantageous for email attachments and uploading or downloading files from websites.
  3. Consolidation of Files: ZIP files enable you to consolidate multiple files into a single archive, reducing the number of files you need to manage. This is useful for organizing projects or distributing software that consists of multiple files.
  4. Password Protection: Many ZIP utilities provide the option to password-protect the archive, adding a layer of security to your files. This is useful when you want to restrict access to the contents of the ZIP file.

Create ZIP Archives and Extract ZIP files using IronZIP

Introduction to the IronZIP library and documentation can be found here. In C# applications, ZIP files can be created and extracted in various ways. IronZIP NuGet package has all the functionalities to archive files in different formats: ZIP, TAR, GZIP, and BZIP2. Below are the sample steps on how to use IronZIP in modern application programming to build next-gen apps to open ZIP files, extract ZIP files, create new ZIP files, etc.

Step 1. Create .NET Core Console Application

Create project

.NET console app can be created using Visual Studio. Open Visual Studio and select Create project. Here you can see various templates to create a project. The easiest way to demonstrate or test the code is by creating a console application. We will select the Console App project template.

How to Open Zip File in C#: Figure 1 - New Project

Enter the project name

In the below window, you can enter the project name, the location of the project to store in the file system and last one is the path to the solution folder. You can keep the solution and project folders the same or have them in different folders.

How to Open Zip File in C#: Figure 2 - Configure Project

Select .NET Framework version

The next step is to select the .NET Framework version for the project. If you want to develop in a specific version, then specify the version you like. Otherwise, always select the latest stable version to create a project. The latest version can be downloaded from the Microsoft website. Then click Create to generate the console application.

How to Open Zip File in C#: Figure 3 - Target Framework

This will create the default project from the template and store the project and solution files in the specified directories. Once the project is created it will look similar to below. Sometimes the class is not used in the program.cs in the latest versions.

// Import necessary namespaces
using System;

// Define the namespace
namespace MyApp // Note: actual namespace depends on the project name.
{
    // Define the Program class
    internal class Program
    {
        // Main method: Entry point of the application
        static void Main(string[] args)
        {
            // Print a welcome message
            Console.WriteLine("Hello, World!");
        }
    }
}
// Import necessary namespaces
using System;

// Define the namespace
namespace MyApp // Note: actual namespace depends on the project name.
{
    // Define the Program class
    internal class Program
    {
        // Main method: Entry point of the application
        static void Main(string[] args)
        {
            // Print a welcome message
            Console.WriteLine("Hello, World!");
        }
    }
}
' Import necessary namespaces
Imports System

' Define the namespace
Namespace MyApp ' Note: actual namespace depends on the project name.
	' Define the Program class
	Friend Class Program
		' Main method: Entry point of the application
		Shared Sub Main(ByVal args() As String)
			' Print a welcome message
			Console.WriteLine("Hello, World!")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

To create a new ZIP file and extract all the ZIP archive files, we can use System.IO.Compression from default libraries. The following code demonstrates how to use ZipFile.OpenRead and ZipFile.Open static methods to open ZIP files or extract ZIP files.

// Import necessary namespaces
using System;
using System.IO;
using System.IO.Compression;

public class ZipExample
{
    public static void Main()
    {
        Console.WriteLine("-----------Zip - Unzip-----------");

        // Method to add a file entry to the ZIP archive
        static void AddEntry(string filePath, ZipArchive zipArchive)
        {
            // Get file name from the file path
            var file = Path.GetFileName(filePath);

            // Create a new entry in the ZIP archive for the file
            zipArchive.CreateEntryFromFile(filePath, file);
        }

        // Name of the ZIP file to be created
        var zip = "myFile.zip";

        // Open or create the ZIP file for updating
        using (ZipArchive archive = ZipFile.Open(zip, ZipArchiveMode.Update))
        {
            // Add files to the archive
            AddEntry("file1.txt", archive);
            AddEntry("file2.txt", archive);
        }

        // Directory where we want to extract the ZIP files
        var dirToExtract = "extract";

        // Create the directory if it does not exist
        if (!Directory.Exists(dirToExtract))
        {
            Directory.CreateDirectory(dirToExtract);
        }

        // Extract the contents of the ZIP file to the specified directory
        ZipFile.ExtractToDirectory(zip, dirToExtract);

        // Indicate that extraction is complete
        Console.WriteLine("Files extracted to: " + dirToExtract);
    }
}
// Import necessary namespaces
using System;
using System.IO;
using System.IO.Compression;

public class ZipExample
{
    public static void Main()
    {
        Console.WriteLine("-----------Zip - Unzip-----------");

        // Method to add a file entry to the ZIP archive
        static void AddEntry(string filePath, ZipArchive zipArchive)
        {
            // Get file name from the file path
            var file = Path.GetFileName(filePath);

            // Create a new entry in the ZIP archive for the file
            zipArchive.CreateEntryFromFile(filePath, file);
        }

        // Name of the ZIP file to be created
        var zip = "myFile.zip";

        // Open or create the ZIP file for updating
        using (ZipArchive archive = ZipFile.Open(zip, ZipArchiveMode.Update))
        {
            // Add files to the archive
            AddEntry("file1.txt", archive);
            AddEntry("file2.txt", archive);
        }

        // Directory where we want to extract the ZIP files
        var dirToExtract = "extract";

        // Create the directory if it does not exist
        if (!Directory.Exists(dirToExtract))
        {
            Directory.CreateDirectory(dirToExtract);
        }

        // Extract the contents of the ZIP file to the specified directory
        ZipFile.ExtractToDirectory(zip, dirToExtract);

        // Indicate that extraction is complete
        Console.WriteLine("Files extracted to: " + dirToExtract);
    }
}
' Import necessary namespaces
Imports System
Imports System.IO
Imports System.IO.Compression

Public Class ZipExample
	Public Shared Sub Main()
		Console.WriteLine("-----------Zip - Unzip-----------")

		' Method to add a file entry to the ZIP archive
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'		static void AddEntry(string filePath, ZipArchive zipArchive)
'		{
'			' Get file name from the file path
'			var file = Path.GetFileName(filePath);
'
'			' Create a new entry in the ZIP archive for the file
'			zipArchive.CreateEntryFromFile(filePath, file);
'		}

		' Name of the ZIP file to be created
		Dim zip = "myFile.zip"

		' Open or create the ZIP file for updating
		Using archive As ZipArchive = ZipFile.Open(zip, ZipArchiveMode.Update)
			' Add files to the archive
			AddEntry("file1.txt", archive)
			AddEntry("file2.txt", archive)
		End Using

		' Directory where we want to extract the ZIP files
		Dim dirToExtract = "extract"

		' Create the directory if it does not exist
		If Not Directory.Exists(dirToExtract) Then
			Directory.CreateDirectory(dirToExtract)
		End If

		' Extract the contents of the ZIP file to the specified directory
		ZipFile.ExtractToDirectory(zip, dirToExtract)

		' Indicate that extraction is complete
		Console.WriteLine("Files extracted to: " & dirToExtract)
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above code, a ZIP file named myFile.zip is used with the system namespace. The Open method is used to open the ZIP file in a specified mode. This can also be used to create new ZIP archive files. Once opened, we can add a new archive entry using the method AddEntry, and then ExtractToDirectory extracts ZIP archive files to the specified directory. If the directory doesn't exist, it is created using Directory.CreateDirectory.

Step 2. Installing IronZIP using NuGet Package Manager

Open Project Manager from Visual Studio and search for the IronZIP package. Then select the latest version and click Install. You can change the version to be installed from the drop-down. Then click Install.

How to Open Zip File in C#: Figure 4 - NuGet Package Manager

Create a ZIP Archive File and add files using IronZIP

How to Open Zip File in C#: Figure 5 - IronZIP

IronZIP is an archive compression and decompression library developed by Iron Software. In addition to the widely used ZIP format, it can also handle TAR, GZIP, and BZIP2.

IronZIP is a C# ZIP Archive Library that prioritizes accuracy, ease of use, and speed. Its user-friendly API enables developers to easily add archive functionality to modern .NET projects in minutes.

IronZIP offers many advantages compared to the System.IO.Compression library. You can specify the compression ratio you want during compression and also use different compression algorithms such as ZIP, TAR, GZIP, BZIP2. It also supports mobile, web, and desktop platforms and various .NET versions.

// Setup: Specify the path for the new ZIP archive
var archivePath = "ironZip.zip";

// Check if the archive already exists, and delete it if so
if (File.Exists(archivePath))
{
    File.Delete(archivePath);
}

// Use IronZIP library to create a new ZIP archive
using (var archive = new IronZipArchive(9)) // Compression level: 9 for maximum compression
{
    // Add files to the ZIP archive
    archive.Add("file1.txt");
    archive.Add("file2.txt");

    // Save the archive to the specified path
    archive.SaveAs(archivePath);
}
// Setup: Specify the path for the new ZIP archive
var archivePath = "ironZip.zip";

// Check if the archive already exists, and delete it if so
if (File.Exists(archivePath))
{
    File.Delete(archivePath);
}

// Use IronZIP library to create a new ZIP archive
using (var archive = new IronZipArchive(9)) // Compression level: 9 for maximum compression
{
    // Add files to the ZIP archive
    archive.Add("file1.txt");
    archive.Add("file2.txt");

    // Save the archive to the specified path
    archive.SaveAs(archivePath);
}
' Setup: Specify the path for the new ZIP archive
Dim archivePath = "ironZip.zip"

' Check if the archive already exists, and delete it if so
If File.Exists(archivePath) Then
	File.Delete(archivePath)
End If

' Use IronZIP library to create a new ZIP archive
Using archive = New IronZipArchive(9) ' Compression level: 9 for maximum compression
	' Add files to the ZIP archive
	archive.Add("file1.txt")
	archive.Add("file2.txt")

	' Save the archive to the specified path
	archive.SaveAs(archivePath)
End Using
$vbLabelText   $csharpLabel

The initial source code sets up by specifying the ZIP archive file name and checking if the specified directory exists. Then we archive the files to create a ZIP file using the Add method. The second parameter in the compression parameter is 1 for lower and 9 for higher. Text files can be compressed to max using 9 without loss, and image files can use lower compression to avoid data loss.

Open the ZIP Archive File Using IronZIP

IronArchive class can also be used to extract the files from the ZIP archive file. All the files are extracted using IronArchive.ExtractArchiveToDirectory, which helps extract all the files to specific directories like below.

// Directory to extract all files from the ZIP archive
var extractionPath = "IronZipFiles";

// Check if the directory exists; if not, create it
if (!Directory.Exists(extractionPath))
{
    Directory.CreateDirectory(extractionPath);
}

// Extract all files from the specified ZIP archive to the directory
IronArchive.ExtractArchiveToDirectory("ironZip.zip", extractionPath);
// Directory to extract all files from the ZIP archive
var extractionPath = "IronZipFiles";

// Check if the directory exists; if not, create it
if (!Directory.Exists(extractionPath))
{
    Directory.CreateDirectory(extractionPath);
}

// Extract all files from the specified ZIP archive to the directory
IronArchive.ExtractArchiveToDirectory("ironZip.zip", extractionPath);
' Directory to extract all files from the ZIP archive
Dim extractionPath = "IronZipFiles"

' Check if the directory exists; if not, create it
If Not Directory.Exists(extractionPath) Then
	Directory.CreateDirectory(extractionPath)
End If

' Extract all files from the specified ZIP archive to the directory
IronArchive.ExtractArchiveToDirectory("ironZip.zip", extractionPath)
$vbLabelText   $csharpLabel

The above code extracts ZIP files to a directory. The code checks if the directory exists, and if not, the ZIP archive file is extracted to the specified directory.

Licensing (Free Trial Available)

For the above code to work, a license key is required. This key needs to be placed in appsettings.json.

{
    "IronZip.LicenseKey": "your license key"
}

A trial license is available for developers upon registering here, and yes, no credit card is required for a trial license. One can provide the email ID and register for a free trial.

Add Files to an Existing ZIP Archive File

Use the static FromFile method from IronZIP to open an existing archive. This method also requires specifying the file name of the new archive that will be created as output.

// Path to a new file to be added to the existing ZIP archive
const string file3 = ".\\image3.png";
var archivePlusPath = "ironZipPlus.zip";

// Open the existing ZIP archive and add a new file
using (var file = IronArchive.FromFile("ironZip.zip", archivePlusPath))
{
    // Add additional files to the existing archive
    file.Add(file3);
}
// Path to a new file to be added to the existing ZIP archive
const string file3 = ".\\image3.png";
var archivePlusPath = "ironZipPlus.zip";

// Open the existing ZIP archive and add a new file
using (var file = IronArchive.FromFile("ironZip.zip", archivePlusPath))
{
    // Add additional files to the existing archive
    file.Add(file3);
}
' Path to a new file to be added to the existing ZIP archive
Const file3 As String = ".\image3.png"
Dim archivePlusPath = "ironZipPlus.zip"

' Open the existing ZIP archive and add a new file
Using file = IronArchive.FromFile("ironZip.zip", archivePlusPath)
	' Add additional files to the existing archive
	file.Add(file3)
End Using
$vbLabelText   $csharpLabel

The code uses the IronArchive.FromFile static method to open the existing ZIP file and then add the new file as an archive entry. Once the file object is disposed, the updated archive is successfully saved.

Updates

The IronZIP library is constantly updated based on feedback from customers/users, and all the updates can be found here.

Conclusion

In conclusion, ZIP file programming is an essential skill to build in modern application development where storage and data transfer costs are charged by cloud host providers. Knowing this skill can help programmers reduce the cost of the application and improve the performance of the application.

By following the installation steps and exploring the provided code examples, developers can quickly leverage the power of IronZIP to handle ZIP tasks with ease. As more and more applications are modernized and moved to the cloud, having a reliable ZIP library like IronZIP equips C# developers with the tools necessary to meet the demands of modern application development. So, embrace the power of IronZIP and unlock new possibilities for working with ZIP files in your C# applications.

IronZIP offers extensive support for its developers. To know more about how IronZIP for C# works visit here. IronZIP offers a free trial license which is a great opportunity to know IronZIP and its features.

Iron Software has various other libraries, explore them to gain more knowledge and update your skills to program/develop modern applications.

Frequently Asked Questions

What is the ZIP file format?

ZIP is an archive entry file system format that supports lossless data compression. It can contain one or more files or directories that may have been compressed using various algorithms, with DEFLATE being the most common.

What are the advantages of using ZIP files?

ZIP files offer advantages such as compression, reduced transfer time, consolidation of multiple files into a single archive, and the option for password protection.

How can I create a .NET Core Console Application to work with ZIP files?

You can create a .NET Core Console Application by using Visual Studio. Choose the Console App project template, specify the project name and location, and select the .NET Framework version you wish to use. IronZIP can be used to handle ZIP files efficiently in the application.

How do I open a ZIP file in C#?

You can open a ZIP file using the System.IO.Compression library by utilizing the ZipFile.OpenRead and ZipFile.Open methods. IronZIP also provides more advanced functionalities for handling ZIP files in C#.

What are the steps to install a ZIP handling library using NuGet Package Manager?

To install IronZIP, open the Project Manager in Visual Studio, search for the IronZIP package, select the latest version, and click Install. You can choose different versions from a dropdown menu if needed.

How do I create and add files to a ZIP archive?

Using IronZIP, you can create a new ZIP archive by specifying the archive path and adding files using the Add method. The archive is then saved using the SaveAs method.

How can I extract files from a ZIP archive?

You can extract files from a ZIP archive using the IronArchive.ExtractArchiveToDirectory method provided by IronZIP. This requires specifying the ZIP file and the directory where the files should be extracted.

Is there a free trial available for this ZIP handling library?

Yes, a trial license is available for developers after registering on the Iron Software website. No credit card is required for the trial.

How do I add files to an existing ZIP archive?

To add files to an existing ZIP archive, use the IronArchive.FromFile static method provided by IronZIP to open the archive, then add new files using the Add method. The updated archive is saved once the process is complete.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.
< PREVIOUS
How to Unzip Files in .NET Core
NEXT >
How to Create Zip File in C# .NET Core

Ready to get started? Version: 2025.6 just released

View Licenses >