跳至頁尾內容
USING IRONZIP

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

ZIP 文件是使用 ZIP 格式壓縮的一個或多個文件或文件夾的集合。 這是一種常見的方法,用於將多個文件或文件夾壓縮和存檔到單個文件中。它們可以減小資料的大小,節省磁碟空間,使得透過網路傳輸文件更加容易。 在這篇文章中,您將了解如何在 C# 中使用 IronZIP 程式庫來處理 ZIP 文件。 您將看到如何以程式化的方式建立、讀取、提取和更新 ZIP 文件,以及如何使用 IronZIP 的各種功能,例如加密、密碼保護和壓縮等級。 在本文結束時,您將能夠輕鬆地使用 IronZIP 在您的 C# 應用程式中處理 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 Package Manager Console。 簡單地運行以下命令:

Install-Package IronZip

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

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

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

您可以輕鬆使用 IronZIP 在資料夾中建立 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# 壓縮資料夾中的文件:圖 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

ExtractArchiveToDirectory 類的 IronZipArchive 方法將 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 通過載入名為 "myZipFile.zip" 的 ZIP 文件和密碼 "myPa55word" 建立一個安全的 IronZipArchive 實例。 如果文件沒有被加密,不要傳遞密碼參數。 然後它檢索並輸出加密 ZIP 存檔中條目名稱(文件和資料夾名稱)的列表。

foreach 方法收集條目名稱,並且 GetArchiveEntryNames 迴圈將每個名稱輸出到控制台。 這演示了如何透過 IronZIP 以簡潔的方式實現受密碼保護的 ZIP 存檔的安全存取和條目資訊檢索。

輸出

如何使用 C# 壓縮資料夾中的文件:圖 4 - 來自之前程式碼範例的輸出

結論

總結,IronZIP 證明是一個處理 ZIP 文件的強大且多功能的 C# 程式庫。 其功能不僅限於基礎的 壓縮提取,還提供密碼保護、加密以及與各種存檔格式相容的功能。 無論您是在建立備份系統、管理電子郵件附件,還是從網路下載文件,IronZIP 都能以簡便和高效的方式簡化這些任務。

透過將 IronZIP 整合到您的 C# 應用程式中,您將獲得一個處理 ZIP 文件的強大工具,增強資料安全性並優化文件傳輸過程。 如有需要,您可以從免費的 試用 中受益。

常見問題

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

您可以使用 IronZIP 通過遍歷目錄中的文件並將它們新增到新的 ZIP 存檔來從資料夾建立 ZIP 文件。使用 IronZipArchive 類並呼叫 SaveAs 方法來保存 ZIP 文件。

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

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

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

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

我可以加密用 C# 建立的 ZIP 文件嗎?

是的,您可以使用 IronZIP 的 Encrypt 方法應用 AES-256 加密來加密 ZIP 文件,以保護存檔中的資料。

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

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

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

是的,您可以使用 IronZIP 在使用方法如 ExtractArchiveToDirectory 時提供密碼來安全地存取文件內容。

使用 IronZIP 管理 ZIP 文件有什麼優勢?

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

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

IronZIP 與 .NET 8、7、6、Core、Standard 和 Framework 相容,使其可靈活整合至各類 C# 專案中。

開發者如何存取 IronZIP 的試用版?

開發者可以存取 IronZIP 網站的授權或下載部分以獲取免費試用版來評估其功能。

使用 ZIP 文件進行資料傳輸的好處是什麼?

ZIP 文件對於資料傳輸有利,因為它們可減少文件尺寸、節省磁碟空間,並便於在線有效傳送多個文件。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話