跳過到頁腳內容
使用 IRONZIP

如何在 C# 中打開 Zip 文件

ZIP 是一種支援無損資料壓縮的歸檔條目檔案系統格式。 ZIP 檔案可能包含一個或多個已壓縮的檔案或目錄。 ZIP 檔案格式支援多種壓縮演算法,其中 DEFLATE 是最常用的。 隨後,許多軟體工具很快便支援了ZIP格式。 主流作業系統廠商早已在系統中加入了對 ZIP 壓縮檔案的支援。微軟從 Windows 98 開始就加入了對 ZIP 檔案的支持,其他廠商也紛紛效法。

在本部落格中,我們將探索一種使用IronZIP開啟 ZIP 壓縮檔案或提取檔案的現代、簡單且高效的方法。 我們將學習有關 ZIP 檔案的基本知識及其優點。 接下來,我們將看到系統命名空間中可用於處理 ZIP 檔案格式的選項。 然後我們將逐步講解如何開啟 ZIP 檔案、將 ZIP 檔案解壓縮到臨時資料夾、建立新的 ZIP 檔案以及在現有 ZIP 檔案中新增檔案。

在軟體應用程式中使用 ZIP 檔案的優勢

1.壓縮:此技術使用各種壓縮演算法(如 Implode、Deflate、Deflate64、bzip2、LZMA、WavPack、PPMd 等)來減少歸檔檔案/資料夾的大小。 2.傳輸時間縮短:檔案越小,傳輸速度越快,尤其是透過網路傳送檔案時。 這對於電子郵件附件以及從網站上傳或下載檔案尤其有利。 3.檔案合併: ZIP 檔案可以將多個檔案合併到一個檔案中,從而減少需要管理的檔案數量。 這對於組織專案或分發由多個文件組成的軟體非常有用。 4.密碼保護:許多 ZIP 工具提供對壓縮檔案進行密碼保護的選項,為您的檔案增加一層安全性。 當您想要限制對 ZIP 檔案內容的存取時,這非常有用。

使用IronZIP建立 ZIP 壓縮檔案並解壓縮 ZIP 文件

IronZIP庫的介紹和文件可以在這裡找到。 在 C# 應用程式中,可以透過多種方式建立和提取 ZIP 檔案。 IronZIP NuGet套件具備將檔案歸檔為不同格式(ZIP、TAR、GZIP 和 BZIP2)的所有功能。以下範例步驟展示如何在現代應用程式編程中使用IronZIP來建立新一代應用程序,例如開啟 ZIP 檔案、解壓縮 ZIP 檔案、建立新的 ZIP 檔案等。

步驟 1. 建立.NET Core控制台應用程式

創建專案

可以使用 Visual Studio 建立.NET控制台應用程式。 開啟 Visual Studio 並選擇"建立專案"。 這裡可以看到各種可用於建立專案的範本。 演示或測試程式碼最簡單的方法是建立一個控制台應用程式。 我們將選擇控制台應用程式專案範本。

如何在 C# 中開啟 Zip 檔案:圖 1 - 新建專案

請輸入項目名稱

在下面的視窗中,您可以輸入項目名稱、項目在檔案系統中的儲存位置,最後一個是解決方案資料夾的路徑。 您可以將解決方案資料夾和專案資料夾放在同一個資料夾中,也可以將它們放在不同的資料夾中。

如何在 C# 中開啟 Zip 檔案:圖 2 - 設定項目

選擇.NET Framework版本

下一步是為專案選擇.NET Framework版本。 如果您想在特定版本中進行開發,請指定您想要的版本。否則,請務必選擇最新的穩定版本來建立專案。 您可以從微軟網站下載最新版本。然後點擊"建立"以產生控制台應用程式。

如何在 C# 中開啟 Zip 檔案:圖 3 - Target Framework

這將根據範本建立預設項目,並將項目和解決方案檔案儲存在指定的目錄中。 專案創建完成後,它將類似於下圖。 有時在最新版本中,program.cs 中不使用類別。

// 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!");
        }
    }
}
$vbLabelText   $csharpLabel

要建立一個新的 ZIP 檔案並提取所有 ZIP 歸檔文件,我們可以使用預設庫中的 System.IO.Compression。 以下程式碼示範如何使用 ZipFile.OpenReadZipFile.Open 靜態方法開啟 ZIP 檔案或提取 ZIP 檔案。

// 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);
    }
}
$vbLabelText   $csharpLabel

在上面的程式碼中,使用了名為 myFile.zip 的 ZIP 文件,並指定了系統命名空間。 Open 方法用於以指定模式開啟 ZIP 檔案。 這也可以用來建立新的 ZIP 壓縮檔。 開啟後,我們可以使用 AddEntry 方法新增新的歸檔條目,然後 ExtractToDirectory 將 ZIP 歸檔檔案提取到指定的目錄。 如果目錄不存在,則使用 Directory.CreateDirectory 建立該目錄。

步驟 2. 使用NuGet套件管理器安裝IronZIP

從 Visual Studio 開啟專案管理器,搜尋IronZIP套件。 然後選擇最新版本並點擊安裝。 您可以從下拉式選單中變更要安裝的版本。 然後點選安裝。

如何在 C# 中開啟 Zip 檔案:圖 4 - NuGet套件管理員

使用IronZIP建立 ZIP 壓縮檔案並新增文件

如何在 C# 中開啟 Zip 檔案:圖 5 - IronZIP

IronZIP是由Iron Software開發的歸檔壓縮和解壓縮函式庫。 除了廣泛使用的 ZIP 格式外,它還可以處理 TAR、GZIP 和 BZIP2 格式。

IronZIP是一個 C# ZIP 歸檔庫,它優先考慮準確性、易用性和速度。 它易於使用的 API 使開發人員能夠在幾分鐘內輕鬆地將存檔功能添加到現代.NET專案中。

System.IO.Compression 函式庫相比, IronZIP具有許多優勢。 您可以在壓縮過程中指定所需的壓縮比,也可以使用不同的壓縮演算法,例如 ZIP、TAR、GZIP、BZIP2。它還支援行動、Web 和桌面平台以及各種.NET版本。

// 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);
}
$vbLabelText   $csharpLabel

初始原始碼透過指定 ZIP 歸檔檔案名稱並檢查指定的目錄是否存在來進行設定。 然後我們使用 Add 方法將檔案歸檔以建立 ZIP 檔案。 壓縮參數中的第二個參數,1 表示較低,9 表示較高。 文字檔案可以壓縮到最高 9 倍而不會遺失數據,圖像檔案可以使用較低的壓縮率以避免數據遺失。

使用IronZIP開啟 ZIP 壓縮文件

IronArchive 類別也可用於從 ZIP 壓縮檔案中擷取檔案。所有檔案均使用 IronArchive.ExtractArchiveToDirectory 提取,該類別可以將所有檔案提取到如下所示的特定目錄。

// 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);
$vbLabelText   $csharpLabel

以上程式碼將 ZIP 檔案解壓縮到指定目錄。 程式碼檢查目錄是否存在,如果不存在,則將 ZIP 歸檔檔案解壓縮到指定目錄。

授權許可(提供免費試用)

要使上述程式碼正常運行,需要許可證密鑰。 此密鑰需要放置在 appsettings.json 中。

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

開發者可在註冊以取得試用許可證,試用許可證無需信用卡。 使用者可以提供電子郵件地址並註冊免費試用。

在現有 ZIP 壓縮檔中新增文件

使用IronZIP的靜態方法 FromFile 開啟現有壓縮檔。此方法還需要指定將要建立的輸出新壓縮檔案的檔案名稱。

// 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);
}
$vbLabelText   $csharpLabel

程式碼使用 IronArchive.FromFile 靜態方法開啟現有的 ZIP 文件,然後將新文件新增為存檔條目。 文件物件被釋放後,更新後的歸檔檔案即成功儲存。

更新

IronZIP庫會根據客戶/用戶的回饋不斷更新,所有更新都可以在這裡找到。

結論

總之,在現代應用程式開發中,儲存和資料傳輸費用由雲端主機供應商收取,因此掌握 ZIP 檔案程式設計是一項至關重要的技能。 掌握這項技能可以幫助程式設計師降低應用程式的成本並提高應用程式的效能。

透過依照安裝步驟和探索提供的程式碼範例,開發人員可以快速利用IronZIP的強大功能輕鬆處理 ZIP 任務。 隨著越來越多的應用程式現代化並遷移到雲端,擁有像IronZIP這樣可靠的 ZIP 程式庫可以為 C# 開發人員提供滿足現代應用程式開發需求所需的工具。 因此,充分利用IronZIP的強大功能,解鎖在 C# 應用程式中處理 ZIP 檔案的新可能性。

IronZIP為其開發者提供全面的支援。 要了解更多關於IronZIP for C# 的工作原理,請造訪這裡。 IronZIP提供免費試用許可證,這是了解IronZIP及其功能的絕佳機會。

Iron Software還擁有各種其他函式庫,探索它們可以獲得更多知識並更新您的技能,從而進行現代應用程式的程式設計/開發。

常見問題解答

如何在 C# 中開啟 ZIP 檔案?

您可以使用 System.IO.Compression 庫在 C# 中開啟 ZIP 檔案。或者,IronZIP 提供了更高級的 ZIP 文件處理功能,提供了一種更簡單、更高效的方式來管理您的歸檔文件。

我如何使用 C# 從 ZIP 壓縮檔案中解壓文件?

使用 IronZIP,您可以通過 IronArchive.ExtractArchiveToDirectory 方法從 ZIP 壓縮檔案中解壓文件。此方法要求您指定 ZIP 檔案和提取目標目錄。

在應用程序開發中使用 ZIP 文件有哪些好處?

ZIP 文件減小了文件大小,這導致傳輸時間更快,並且能夠將多個文件合併成一個壓縮檔案。IronZIP 通過如壓縮比設置和支持多個格式的附加功能增強了這些優勢。

如何在 C# 中將文件添加到現有的 ZIP 檔案中?

要使用 IronZIP 向現有的 ZIP 壓縮檔案添加文件,請利用 IronArchive.FromFile 方法打開壓縮檔,然後使用 Add 方法加入新文件。保存更新的壓縮檔以完成過程。

我可以使用 IronZIP 創建新的 ZIP 文件並將文件添加進去嗎?

是的,利用 IronZIP,您可以通過指定壓縮檔路徑並使用 Add 方法添加文件來創建新的 ZIP 文件。然後使用 SaveAs 方法保存壓縮檔。

如何使用 NuGet 套件管理器安裝 IronZIP?

要通過 NuGet 套件管理器安裝 IronZIP,請在 Visual Studio 中打開專案管理器,搜索 IronZIP,選擇最新版本,然後點擊安裝。這將把 IronZIP 添加到您的專案中,啟用 ZIP 文件管理功能。

IronZIP 是否支持多種壓縮格式?

是的,IronZIP 支持多種壓縮格式,包括 ZIP、TAR、GZIP 和 BZIP2,提供應用程序需求的靈活性。

是否提供 IronZIP 的免費試用版?

是的,IronZIP 為開發者提供免費試用。您可以在 Iron Software 官網上註冊獲取試用,無需信用卡。

IronZIP 為什麼適合現代應用程序開發?

IronZIP 因其易用性、速度和跨平台兼容性而聞名。這些功能,再加上其高級功能,使其成為現代應用程序開發的理想選擇。

Curtis Chau
技術作家

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

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

鋼鐵支援團隊

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