
如何在 C# 中打開 Zip 文件
ZIP是一種存檔進入文件系統格式,支援無損資料壓縮。 ZIP文件可能包含一個或多個文件或目錄,這些文件或目錄可能已被壓縮。 ZIP文件格式允許多種壓縮算法,儘管DEFLATE是最常見的。 ZIP格式隨後被許多軟體工具迅速支援。 主流操作系統供應商已經長期包含了對ZIP存檔的支援。Microsoft自Windows 98起就提供了對ZIP文件的支援,其餘的則緊隨其後。
在這篇部落格中,我們將探索一種現代、簡單且高效的方式來開啟ZIP存檔文件或解壓文件,使用IronZIP。 我們將學習有關ZIP文件的一般知識及其優點。 然後,我們將看到系統命名空間中可用的選項來處理ZIP文件格式。 接著,我們將逐步探索開啟ZIP文件、將ZIP文件提取到臨時文件夾、新建ZIP文件以及向現有ZIP文件中新增文件的步驟。
在軟體應用中使用ZIP文件的優勢
- **壓縮:**此技術使用多種壓縮算法,如Implode、Deflate、Deflate64、bzip2、LZMA、WavPack、PPMd等,來減少存檔文件/文件夾的大小。
- **減少傳輸時間:**較小的文件大小意味著傳輸時間更短,特別是在通過互聯網傳輸文件時。 這特別有利於電子郵件附件以及從網站上傳或下載文件。
- **文件合併:**ZIP文件使您可以將多個文件合併成一個存檔,減少您需要管理的文件數量。 這對於組織項目或分發包含多個文件的軟體十分有用。
- **密碼保護:**許多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,然後選擇建立專案。 在這裡,您可以看到各種用於建立專案的範本。 展示或測試程式碼的最簡便方法是建立控制台應用程式。 我們將選擇控制台應用專案範本。

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

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

這將從範本建立預設專案並將專案和解決方案文件存放在指定的目錄中。 專案建立後,將類似於下方。 有時在最新版本中類別在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
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要建立新的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
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
Sub AddEntry(ByVal filePath As String, ByVal zipArchive As ZipArchive)
' Get file name from the file path
Dim file = Path.GetFileName(filePath)
' Create a new entry in the ZIP archive for the file
zipArchive.CreateEntryFromFile(filePath, file)
End Sub
' 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在上述程式碼中,使用名為myFile.zip的ZIP文件和系統命名空間。 Open方法用於在指定模式下開啟ZIP文件。 這也可用於建立新的ZIP存檔文件。 開啟後,我們可以使用方法ExtractToDirectory將ZIP存檔文件提取到指定的目錄。 如果目錄不存在,則使用Directory.CreateDirectory建立。
步驟2. 使用NuGet包管理器安裝IronZIP
從Visual Studio開啟專案管理器並搜尋IronZIP包。 然後選擇最新版本,然後點選安裝。 您可以從下拉選單更改要安裝的版本。 然後點選安裝。

使用IronZIP建立ZIP存檔文件並新增文件

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
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初始源程式碼通過指定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
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)上述程式碼將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 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程式碼使用IronArchive.FromFile靜態方法來打開現有ZIP文件,然後將新文件新增為存檔條目。 一旦文件物件被處置後,更新的存檔已成功保存。
更新
IronZIP程式庫基於客戶/使用者的反饋不斷進行更新,所有更新可以在此處找到。
結論
總之,ZIP文件編程是現代應用開發中必備的技能之一,特別是在雲端提供商對儲存和資料傳輸收費的情況下。 掌握這一技能可以幫助程式員降低應用程式成本,並提高應用程式性能。
透過遵循安裝步驟並探索提供的程式碼範例,開發者可以快速運用IronZIP的強大功能輕鬆處理ZIP任務。 隨著越來越多的應用程式現代化並遷移至雲端,擁有像IronZIP這樣可靠的ZIP程式庫,為C#開發者提供了滿足現代應用開發需求的工具。 因此,擁抱IronZIP的力量,為您的C#應用程式開啟處理ZIP文件的新可能性。
IronZIP為其開發者提供了廣泛的支援。 欲了解更多有關IronZIP for C#的運作情況,請存取此處。 IronZIP提供免費試用授權,這是一個了解IronZIP及其功能的絕佳機會。
Iron Software有其他多種程式庫,探索它們以獲取更多知識,並更新您的技能以編寫/開發現代應用程式。

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


