跳至頁尾內容
USING IRONZIP

如何在 C# 中打開 Zip 文件

ZIP是一種存檔進入文件系統格式,支援無損資料壓縮。 ZIP文件可能包含一個或多個文件或目錄,這些文件或目錄可能已被壓縮。 ZIP文件格式允許多種壓縮算法,儘管DEFLATE是最常見的。 ZIP格式隨後被許多軟體工具迅速支援。 主流操作系統供應商已經長期包含了對ZIP存檔的支援。Microsoft自Windows 98起就提供了對ZIP文件的支援,其餘的則緊隨其後。

在這篇部落格中,我們將探索一種現代、簡單且高效的方式來開啟ZIP存檔文件或解壓文件,使用IronZIP。 我們將學習有關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控制台應用程式

建立專案

.NET控制台應用程式可以使用Visual Studio建立。 開啟Visual Studio,然後選擇建立專案。 在這裡,您可以看到各種用於建立專案的範本。 展示或測試程式碼的最簡便方法是建立控制台應用程式。 我們將選擇控制台應用專案範本。

如何在C#中開啟ZIP文件:圖1 - 新專案

輸入專案名稱

在下面的窗口中,您可以輸入專案名稱、存放在文件系統的專案位置和解決方案文件夾的路徑。 您可以保持解決方案和專案文件夾相同,也可以放在不同的文件夾中。

如何在C#中開啟ZIP文件:圖2 - 配置專案

選擇.NET Framework版本

下一步是為專案選擇.NET Framework的版本。 如果您想在特定版本中開發,則請指定您喜歡的版本。否則,請始終選擇最新的穩定版本來建立專案。 可以從Microsoft網站下載最新版本。然後點選建立以生成控制台應用程式。

如何在C#中開啟ZIP文件:圖3 - 目標架構

這將從範本建立預設專案並將專案和解決方案文件存放在指定的目錄中。 專案建立後,將類似於下方。 有時在最新版本中類別在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!");
        }
    }
}
' 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

要建立新的ZIP文件並提取所有ZIP存檔文件,我們可以使用預設庫中的System.IO.Compression。 以下程式碼演示如何使用ZipFile.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);
    }
}
' 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

在上述程式碼中,使用名為myFile.zip的ZIP文件和系統命名空間。 Open方法用於在指定模式下開啟ZIP文件。 這也可用於建立新的ZIP存檔文件。 開啟後,我們可以使用方法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專案中。

IronZIP相比於System.IO.Compression程式庫提供了許多優勢。 在壓縮過程中,您可以指定想要的壓縮比例,並且還可以使用不同的壓縮算法,如ZIP、TAR、GZIP、BZIP2。它還支援移動、網頁和桌面平台以及各種.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);
}
' 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

初始源程式碼通過指定ZIP存檔文件名並檢查指定目錄是否存在來進行設定。 然後使用Add方法將文件存檔以建立ZIP文件。 壓縮參數中的第二個參數為1表示較低壓縮,9表示較高壓縮。 文字文件可以使用9進行最大壓縮而無損,而圖像文件可以使用較低壓縮以避免資料丟失。

使用IronZIP開啟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);
' 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

上述程式碼將ZIP文件提取到目錄中。 程式碼檢查目錄是否存在,如果不存在,則將ZIP存檔文件提取到指定的目錄。

許可(免費試用可用)

要使上述程式碼正常運作,需要授權金鑰。 此金鑰需放置於appsettings.json中。

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

開發者可在此處註冊獲得試用授權,是的,試用授權不需要信用卡。 可以提供電子郵件ID並註冊免費試用。

向現有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);
}
' 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

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

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

Iron 支援團隊

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