跳過到頁腳內容
使用 IRONZIP

如何使用 C# 在資料夾中壓縮檔案

ZIP 檔案是包含一個或多個使用 ZIP 格式的壓縮檔案或資料夾的檔案。 這是一種常見的將多個檔案或資料夾壓縮並歸檔到單一檔案中的方法。它可以減小資料大小,節省磁碟空間,並使透過網路傳輸檔案更加容易。 本文將介紹如何使用IronZIP函式庫在C#中處理ZIP檔。 您將了解如何以程式設計方式建立、讀取、提取和更新 ZIP 文件,以及如何使用 IronZIP 的各種功能,例如加密、密碼保護和壓縮等級。 閱讀本文,您將能夠輕鬆地在 C# 應用程式中使用 IronZIP 處理 ZIP 檔案。

本文將涵蓋以下內容

  1. 在我們的專案中安裝 IronZIP
  2. 建立 ZIP 文件
  3. 建立受密碼保護的 ZIP 文件
  4. 解壓縮 ZIP 文件
  5. 解壓縮受密碼保護的 ZIP 文件
  6. 存取現有 ZIP 壓縮包

IronZip是什麼?

IronZIP是一個功能強大且用途廣泛的 C# ZIP 歸檔庫,可讓您以程式設計方式建立、讀取和提取 ZIP 檔案。 它支援多種歸檔格式,例如ZIPTARGZIPBZIP2 。 它還支援密碼保護、加密和壓縮等級。 IronZIP 與 .NET 8、7、6、Core、Standard 和 Framework 相容。

IronZIP 可以幫助您處理使用 ZIP 檔案的各種場景和優勢,例如:

1.建立備份系統:您可以使用 IronZIP 將重要檔案和資料夾壓縮並加密到 ZIP 檔案中,並將其儲存在安全的位置。 這樣可以節省磁碟空間,並保護您的資料免受未經授權的存取。 2.傳送電子郵件附件:您可以使用 IronZIP 將電子郵件附件壓縮成 ZIP 文件,從而減少附件的大小。這有助於避免超出檔案大小限制,並加快傳輸速度。 3.從網路下載文件:您可以使用 IronZIP 從網路下載和提取 ZIP 文件,例如軟體包、文件、圖像和其他類型的文件。 這可以幫助您節省頻寬和時間,並輕鬆存取所需文件。

IronZIP入門指南

在編寫代碼之前,您需要在 C# 專案中安裝 IronZIP NuGet 套件。 IronZIP 是一個受歡迎的壓縮函式庫,可透過 NuGet 取得。

安裝 IronZIP 庫

若要安裝 IronZIP,您可以使用 Visual Studio 中的 NuGet 套件管理器控制台。 只需執行以下指令即可:

Install-Package IronZip

或者,您可以直接從IronZIP官方網站下載軟體包。安裝完成後,您可以透過在 C# 程式碼頂部新增以下命名空間來開始使用。

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

在資料夾中建立 C# ZIP 文件

您可以使用 IronZIP 輕鬆地在資料夾中建立 ZIP 檔案。以下程式碼會將指定目錄中的所有檔案壓縮成 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");
        }
    }
}
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

上述 C# 程式碼使用 IronZIP 函式庫將所有檔案壓縮到一個 ZIP 檔案中。該程式碼執行以下操作:

  • 宣告一個名為fileArray字串數組,並將Directory.GetFiles方法的結果賦值給它,並將目錄路徑("D:\Docs")作為參數傳遞。 此方法傳回一個字串數組,其中包含指定目錄中所有檔案的完整名稱。
  • 建立IronZipArchive類別的新實例,該實例表示記憶體中的 ZIP 檔案。 這個實例被賦值給一個名為archive變量,並用using語句包裹起來,以確保在程式碼區塊結束時釋放 ZIP 檔案。
  • 使用foreach循環遍歷fileArray數組,對於每個文件,呼叫archive物件的Add方法,並將文件名作為參數傳遞。 此方法會在 ZIP 檔案中新增一個條目,其名稱和內容與檔案相同。
  • 呼叫archive物件的SaveAs方法,並將 ZIP 檔案的名稱("myZipFile.zip")傳遞為參數。 此方法將 ZIP 壓縮檔案儲存到目前檔案系統中的一個檔案中。

這樣,您只需幾行程式碼即可輕鬆建立新的 ZIP 壓縮檔案。

輸出

輸出結果如下:

如何使用 C# 將資料夾中的檔案壓縮:圖 1 - 上一個程式碼範例的輸出文件

建立受密碼保護的 ZIP 文件

IronZIP 提供了一種建立受密碼保護的 ZIP 檔案的簡單方法。 以下程式碼範例將壓縮檔案並建立一個帶有密碼的新 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");
        }
    }
}
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

archive.Encrypt("myPa55word", EncryptionMethods.AES256);這行程式碼使用 IronZIP 為 ZIP 壓縮封包設定密碼("myPa55word")。它透過對壓縮包應用 AES-256 加密來增強安全性,確保只有擁有正確密碼的使用者才能存取其內容。 此功能對於在 C# 應用程式中儲存或傳輸敏感資料時提供保護非常有用。 您需要在第二個參數中傳遞指定的加密演算法模式。

文件已加密,如下所示。

輸出

如何使用 C# 將資料夾中的檔案壓縮成 ZIP 檔案:圖 2 - 上一個程式碼範例中輸出的加密文件

我們已經看到了透過循環遍歷指定路徑中的目錄來建立 ZIP 檔案的示範。 現在,讓我們來看一個解壓縮檔案的例子。

從 ZIP 壓縮包中提取文件

IronZIP 提供了一種在 C# 中從 ZIP 檔案中提取檔案的方法。 以下程式碼範例將提取 ZIP 壓縮包中的壓縮檔案。

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

程式碼IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles");使用 IronZIP 從 "myZipFile.zip" 中提取所有文件,並將它們放置在 "myExtractedFiles" 目錄中。 這種簡潔的方法簡化了在 C# 中提取 ZIP 存檔的過程,為文件提取任務提供了一個便捷的解決方案。

輸出

輸出結果如下:

如何使用 C# 將資料夾中的檔案壓縮:圖 3 - 上一個程式碼範例的輸出文件

如何從受密碼保護的 ZIP 檔案中提取文件

IronZIP 還提供了一種提取受密碼保護的 ZIP 檔案的方法。 以下程式碼將使用 IronZIP 方法從指定的 ZIP 檔案中提取所有現有檔案和目錄。

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

IronZipArchive類別的ExtractArchiveToDirectory方法將 ZIP 檔案中的所有條目提取到指定的目錄中。 它會向該方法傳遞三個參數:ZIP 檔案的路徑("myZipFile.zip")、目標目錄的路徑("myExtractedFiles")和 ZIP 檔案的密碼("myPa55word")。

這樣,您就可以輕鬆提取受密碼保護的 ZIP 檔案。

如何存取現有存檔

IronZIP 提供了存取現有存檔並查看文件中所有條目的方法。

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

提供的 C# 程式碼使用 IronZIP 建立一個安全的IronZipArchive實例,方法是載入一個名為"myZipFile.zip"的 ZIP 文件,密碼為"myPa55word"。 如果文件未加密,則不要傳遞密碼參數。 然後,它會檢索並列印加密 ZIP 檔案中的條目名稱(檔案和資料夾名稱)清單。

GetArchiveEntryNames方法收集條目名稱,並使用foreach循環將每個名稱輸出到控制台。 這展示了 IronZIP 如何以簡潔的方式安全地存取和檢索受密碼保護的 ZIP 存檔中的條目資訊。

輸出

如何使用 C# 壓縮資料夾中的檔案:圖 4 - 上一個程式碼範例的輸出

結論

總之,IronZIP 被證明是一個強大且多功能的 C# 函式庫,可用於處理 ZIP 檔案。 它的功能不僅限於基本的壓縮提取,還提供密碼保護、加密以及與各種存檔格式的兼容性等功能。 無論您是建立備份系統、管理電子郵件附件或從網路下載文件,IronZIP 都能以簡單且有效率的方式簡化這些任務。

透過將 IronZIP 整合到您的 C# 應用程式中,您可以獲得一個強大的工具來處理 ZIP 檔案、增強資料安全性並優化檔案傳輸過程。 您可以根據需要享受免費試用

常見問題解答

如何在 C# 中從資料夾建立 ZIP 檔案?

您可以使用 IronZIP 從資料夾中建立 ZIP 檔案,方法是反覆檢視目錄中的檔案,然後將它們加入新的 ZIP 存檔。使用 IronZipArchive 類,並呼叫 SaveAs 方法來儲存 ZIP 檔案。

如何在 C# 專案中安裝 IronZIP?

使用 Visual Studio 中的 NuGet Package Manager 在您的 C# 專案中安裝 IronZIP。在套件管理員控制台執行指令 Install-Package IronZip 或從 IronZIP 官方網站下載。

IronZIP 支援哪些格式的 ZIP 檔案處理?

IronZIP 支援多種歸檔格式,包括 ZIP、TAR、GZIP 和 BZIP2,可針對不同的壓縮和歸檔需求提供彈性。

我可以加密 C# 建立的 ZIP 檔案嗎?

是的,您可以使用 IronZIP 加密 ZIP 檔案,方法是套用 AES-256 加密的 Encrypt 方法,以確保歸檔內資料的安全。

如何使用 C# 從 ZIP 檔案中萃取檔案?

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

是否可以在 C# 中處理受到密碼保護的 ZIP 檔案?

是的,您可以使用 IronZIP 處理受密碼保護的 ZIP 檔案,只要在使用 ExtractArchiveToDirectory 等方法時提供密碼,即可安全地存取內容。

使用 IronZIP 進行 ZIP 檔案管理有哪些優點?

IronZIP 透過提供加密、密碼保護和支援多種檔案格式等功能,簡化檔案備份、電子郵件附件管理和網頁下載等工作。

IronZIP 是否支援 .NET 8 及其他版本?

IronZIP 與 .NET 8、7、6、Core、Standard 及 Framework 相容,可靈活整合至各種 C# 專案。

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

開發人員可以造訪 IronZIP 網站的授權或下載區,取得 IronZIP 的免費試用版,以評估其功能。

使用 ZIP 檔案進行資料傳輸有什麼好處?

ZIP 檔案有助於資料傳輸,因為它們可縮小檔案大小、節省磁碟空間,並使透過網際網路有效傳送多個檔案變得更容易。

Curtis Chau
技術作家

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

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