跳過到頁腳內容
使用 IRONZIP

如何使用 C# 壓縮文件夾中的文件

ZIP files are files that contain one or more compressed files or folders using the ZIP format. It is a common way of compressing and archiving multiple files or folders into a single file. They can reduce the size of the data, save disk space, and make it easier to transfer files over the internet. In this article, you will learn how to work with ZIP files in C# using the IronZIP library. You will see how to create, read, extract, and update ZIP files programmatically, as well as how to use various features of IronZIP, such as encryption, password protection, and compression levels. By the end of this article, you will be able to use IronZIP to handle ZIP files in your C# applications with ease.

What we will Cover in this Article

  1. Install IronZIP within our Project
  2. Create a ZIP file
  3. Create Password Protected ZIP file
  4. Extract ZIP file
  5. Extract Password Protected ZIP File
  6. Access Existing ZIP archive

What is IronZip?

IronZIP is a powerful and versatile C# ZIP archive library that allows you to create, read, and extract ZIP files programmatically. It supports various archive formats, such as ZIP, TAR, GZIP, and BZIP2. It also supports password protection, encryption, and compression levels. IronZIP is compatible with .NET 8, 7, 6, Core, Standard, and Framework.

IronZIP can help you handle various use cases and benefits of working with ZIP files, such as:

  1. Creating a backup system: You can use IronZIP to compress and encrypt your important files and folders into a ZIP archive and store them in a secure location. This way, you can save disk space and protect your data from unauthorized access.
  2. Sending email attachments: You can use IronZIP to reduce the size of your email attachments by compressing them into a ZIP file. This can help you avoid exceeding the file size limit and speed up the transmission process.
  3. Downloading files from the web: You can use IronZIP to download and extract ZIP files from the web, such as software packages, documents, images, and other types of files. This can help you save bandwidth and time and access the files you need with ease.

Getting Started with IronZIP

Before writing the code, you need to install the IronZIP NuGet Package in your C# project. IronZIP is a popular compression library available via NuGet.

Installing the IronZIP Library

To install IronZIP, you can use the NuGet Package Manager Console in Visual Studio. Simply run the following command:

Install-Package IronZip

Alternatively, you can download the package directly from the official IronZIP website. Once installed, you can get started by adding the following namespace to the top of your C# code.

using IronZip;
using IronZip;
Imports IronZip
$vbLabelText   $csharpLabel

Creating C# ZIP Files in a Folder

You can easily create ZIP files in a folder using IronZIP. The following code will zip all the files from the specified directory.

using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
Imports System
Imports System.IO
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Get all files from the specified directory
		Dim fileArray() As String = Directory.GetFiles("D:\Docs\")

		' Create a new ZIP archive
		Using archive = New IronZipArchive()
			' Iterate through each file and add it to the archive
			For Each file In fileArray
				archive.Add(file) ' Add files to the ZIP
			Next file
			' Save the archive to a file
			archive.SaveAs("myZipFile.zip")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

The above C# code uses the IronZIP library to compress all the files into a single ZIP file. The code does the following:

  • Declares a string array named fileArray and assigns it the result of the Directory.GetFiles method, passing the path of the directory ("D:\Docs") as a parameter. This method returns an array of strings containing the full names of all the files in the specified directory.
  • Creates a new instance of the IronZipArchive class, which represents a ZIP archive in memory. The instance is assigned to a variable named archive and is wrapped in a using statement, which ensures that the ZIP archive is disposed of when the code block ends.
  • Iterates over the fileArray array using a foreach loop, and for each file, it calls the Add method of the archive object, passing the file name as a parameter. This method adds a new entry to the ZIP archive, with the same name and content as the file.
  • Calls the SaveAs method of the archive object, passing the name of the ZIP file (“myZipFile.zip”) as a parameter. This method saves the ZIP archive to a file in the current file system.

In this way, you can easily create new ZIP archives using just a few lines of code.

Output

Output is as follows:

How to Zip Files in Folder Using C#: Figure 1 - Output files from the previous code example

Create a Password Protected ZIP file

IronZIP provides an easy method to create password-protected ZIP files. The following code sample will compress files and create a new ZIP file with a password.

using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Set Password and Encryption Method
            archive.Encrypt("myPa55word", EncryptionMethods.AES256);
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Set Password and Encryption Method
            archive.Encrypt("myPa55word", EncryptionMethods.AES256);
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
Imports System
Imports System.IO
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Get all files from the specified directory
		Dim fileArray() As String = Directory.GetFiles("D:\Docs\")

		' Create a new ZIP archive
		Using archive = New IronZipArchive()
			' Iterate through each file and add it to the archive
			For Each file In fileArray
				archive.Add(file) ' Add files to the ZIP
			Next file
			' Set Password and Encryption Method
			archive.Encrypt("myPa55word", EncryptionMethods.AES256)
			' Save the archive to a file
			archive.SaveAs("myZipFile.zip")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

The line archive.Encrypt("myPa55word", EncryptionMethods.AES256); sets a password ("myPa55word") for a ZIP archive using IronZIP. It enhances security by applying AES-256 encryption to the archive, ensuring that only users with the correct password can access its contents. This feature is valuable for protecting sensitive data during storage or transfer within C# applications. You need to pass the specified mode of the Encryption algorithm in the second parameter.

The file is encrypted as shown below.

Output

How to Zip Files in Folder Using C#: Figure 2 - Outputted encrypted file from the previous code example

We have seen the demonstration of creating a ZIP file by looping through the directories from the specified path. Now, let's move toward the example of unzipping files.

Extracting Files from ZIP Archive

IronZIP provides a method to extract files from a ZIP archive in C#. The following code sample will extract the compressed file within a ZIP archive.

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles");
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles");
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Extract all files from the ZIP archive to the specified directory
		IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles")
	End Sub
End Class
$vbLabelText   $csharpLabel

The code IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles"); uses IronZIP to extract all files from "myZipFile.zip" and places them in the "myExtractedFiles" directory. This concise method simplifies the process of extracting ZIP archives in C#, providing a convenient solution for file extraction tasks.

Output

Output is as follows:

How to Zip Files in Folder Using C#: Figure 3 - Outputted files from the previous code example

How to Extract from a Password-Protected ZIP File

IronZIP also provides a method to extract password-protected ZIP files. The following code will use the IronZIP method to extract all the existing files and directories from the specified ZIP file.

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the password-protected ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles", "myPa55word");
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the password-protected ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles", "myPa55word");
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Extract all files from the password-protected ZIP archive to the specified directory
		IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles", "myPa55word")
	End Sub
End Class
$vbLabelText   $csharpLabel

The ExtractArchiveToDirectory method of the IronZipArchive class extracts all the entries from a ZIP archive to a specified directory. It passes three arguments to the method: the path of the ZIP file (“myZipFile.zip”), the path of the destination directory (“myExtractedFiles”), and the password of the ZIP file (“myPa55word”).

In this way, you can easily extract password-protected ZIP files.

How to Access an Existing Archive

IronZIP provides methods to access the existing archive and view all the entries present in the file.

using System;
using System.Collections.Generic;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Open an existing ZIP archive with a password
        using (var archive = new IronZipArchive("myZipFile.zip", "myPa55word"))
        {
            // Get entries list
            List<string> names = archive.GetArchiveEntryNames();
            // Iterate through each entry name and print it
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Open an existing ZIP archive with a password
        using (var archive = new IronZipArchive("myZipFile.zip", "myPa55word"))
        {
            // Get entries list
            List<string> names = archive.GetArchiveEntryNames();
            // Iterate through each entry name and print it
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Open an existing ZIP archive with a password
		Using archive = New IronZipArchive("myZipFile.zip", "myPa55word")
			' Get entries list
			Dim names As List(Of String) = archive.GetArchiveEntryNames()
			' Iterate through each entry name and print it
			For Each name As String In names
				Console.WriteLine(name)
			Next name
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

The provided C# code uses IronZIP to create a secure IronZipArchive instance by loading a ZIP file named "myZipFile.zip" with the password "myPa55word". Don't pass the password parameter if the file is not encrypted. It then retrieves and prints the list of entry names (file and folder names) within the encrypted ZIP archive.

The GetArchiveEntryNames method gathers the entry names, and a foreach loop outputs each name to the console. This demonstrates how IronZIP enables secure access and retrieval of entry information from password-protected ZIP archives in a concise manner.

Output

How to Zip Files in Folder Using C#: Figure 4 - Output from the previous code example

Conclusion

In conclusion, IronZIP proves to be a robust and versatile C# library for working with ZIP files. Its capabilities extend beyond basic compression and extraction, offering features such as password protection, encryption, and compatibility with various archive formats. Whether you're creating backup systems, managing email attachments, or downloading files from the web, IronZIP streamlines these tasks with simplicity and efficiency.

By integrating IronZIP into your C# applications, you gain a powerful tool for handling ZIP files, enhancing data security, and optimizing file transfer processes. You can benefit from a free trial as needed.

常見問題解答

如何在 C# 中從資料夾建立 ZIP 文件?

您可以使用 IronZIP 從資料夾建立 ZIP 文件,方法是遍歷目錄中的文件,並將它們添加到新的 ZIP 壓縮檔案中。使用 IronZipArchive 類別並調用 SaveAs 方法以保存 ZIP 文件。

如何在 C# 項目中安裝 IronZIP?

通過在 Visual Studio 的 NuGet 套件管理器中使用命令 Install-Package IronZip 在 C# 專案中安裝 IronZIP,或從官方 IronZIP 網站下載。

IronZIP 支持哪些格式的 ZIP 文件處理?

IronZIP 支持包括 ZIP、TAR、GZIP 和 BZIP2 在內的多種壓縮格式,提供不同壓縮和存檔需求的靈活性。

我可以加密在 C# 中創建的 ZIP 文件嗎?

是的,您可以使用 IronZIP 的 Encrypt 方法將 AES-256 加密應用於您的壓縮檔案中的數據進行加密。

如何在 C# 中從 ZIP 文件中提取文件?

要使用 IronZIP 從 ZIP 檔案中提取文件,請使用 ExtractArchiveToDirectory 方法,指定來源 ZIP 文件和目標目錄。

是否可以在 C# 中處理受密碼保護的 ZIP 文件?

是的,您可以通過在使用 ExtractArchiveToDirectory 等方法時提供密碼來處理受密碼保護的 ZIP 文件,以安全地訪問內容。

使用 IronZIP 進行 ZIP 文件管理有哪些優勢?

IronZIP 簡化了文件備份、電子郵件附件管理和網絡下載等任務,提供加密、密碼保護和多種壓縮格式支持等功能。

IronZIP 支持 .NET 8 和其他版本嗎?

IronZIP 與 .NET 8、7、6、Core、Standard 和 Framework 兼容,便於整合到各種 C# 項目中。

開發人員如何獲取 IronZIP 的試用版本?

開發人員可以通過訪問 IronZIP 網站的授權或下載部分來訪問免費試用版本,以評估其功能。

使用 ZIP 文件進行數據傳輸有何好處?

ZIP 文件有助於減少文件大小、節省磁碟空間,並便於通過互聯網高效傳輸多個文件。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。