.NET 幫助

Sharpziplib 擷取 ZIP C#(開發者操作方式)

在當今的數位環境中,數據管理至關重要,擁有高效的壓縮和解壓縮工具是關鍵。 .NET 生態系統中一個突出的工具是SharpZipLib。 在本文中,我們將深入探討 SharpZipLib,探索其功能、應用以及如何將其整合到您的 .NET 專案中。

什麼是SharpZipLib?

SharpZipLib 是一個功能豐富的開源壓縮庫,用於 .NET,完全以 C# 編寫。 它為各種壓縮格式提供全面支持,包括ZIP、GZip和Tar。 由專注的社群開發,SharpZipLib 提供廣泛的功能,以高效地壓縮和解壓縮檔案。

功能與能力

  1. 支持多種壓縮格式:SharpZipLib 支持流行的壓縮格式,如 ZIP、GZip 和 Tar,以滿足各種使用案例和需求。

  2. 基於流的操作:該庫運行於流上,使開發者能夠使用來自各種來源的數據,包括文件、內存流或網絡流。 這種靈活性促進了應用程序不同部分的無縫整合。

  3. 壓縮級別:開發者可以根據他們的具體需求微調壓縮級別,以平衡壓縮比和處理速度。

  4. 密碼保護:SharpZipLib允許創建受密碼保護的ZIP檔案,透過使用指定的密碼加密內容來確保資料安全。

  5. 錯誤處理與恢復:穩健的錯誤處理機制使開發者在壓縮和解壓操作中能夠優雅地處理異常情況。 此外,SharpZipLib 支援從損壞的檔案中恢復,提高了可靠性。

使用案例

  1. 文件壓縮和封存:SharpZipLib 是需要壓縮和封存文件的應用程式的理想選擇,例如備份工具、文件管理工具或數據匯出功能。

  2. 網路服務與 API:處理檔案傳輸或數據交換的網路服務通常受益於壓縮,從而減少帶寬使用。 SharpZipLib 可以無縫整合到這些服務中,以有效壓縮傳出的數據或解壓縮接收到的載荷。

  3. 桌面應用程式: 處理大型資料集或資源檔案的桌面應用程式可以利用 SharpZipLib 壓縮檔案進行存儲或分發。 這對於軟體安裝程式或數據同步工具尤其有用。

  4. 數據備份與存儲:需要定期備份或以壓縮格式存儲數據的應用程式可以使用SharpZipLib自動化備份過程並有效節省存儲空間。

SharpZipLib 的優勢

  1. 開源:作為開源庫,SharpZipLib 鼓勵合作和社群貢獻,確保持續改進並適應不斷演變的需求。

  2. 跨平台相容性:SharpZipLib 使用 C# 編寫,針對 .NET 框架,與多種平台相容,包括 Windows、Linux 和 macOS,提高了其多樣性。

  3. 輕量且高效: SharpZipLib 專為輕量和高效而設計,在提供高性能壓縮和解壓能力的同時,將資源消耗降至最低。

  4. 豐富的文檔和支持:完整的文檔和社群支持讓開發者在使用SharpZipLib時更容易進行集成和解決問題。

建立 C# Visual Studio 專案

  1. 打開 Visual Studio,然後點擊「建立新專案」選項。

  2. 根據您的需求選擇合適的項目模板(例如,控制台應用程式、Windows Forms 應用程式)。

    Sharpziplib 解壓縮 ZIP C#(開發人員如何使用):圖 1 - 對於新專案,選擇 C# 中的 主控台應用程式。

  3. 指定專案名稱和位置,然後點擊「下一步」。

    Sharpziplib 解壓 ZIP C#(開發者如何操作):圖2 - 通過指定專案名稱、位置和解決方案名稱來配置專案。 接下來,選擇 .NET Framework,然後點擊建立。

  4. 從其他資訊中選取最新的 .NET Framework。 按「建立」以建立專案。

安裝過程

將 SharpZipLib 整合到您的 .NET 專案中:

  1. 在您的Visual Studio IDE C# ConsoleApp 中,右鍵點擊解決方案總管中的專案,然後選擇“管理 NuGet 套件...”

  2. 在 NuGet 套件管理器窗口中,搜索 "SharpZipLib"。

    Sharpziplib 解壓縮 ZIP C#(開發者的工作原理):圖 3 - 使用「解決方案的 NuGet 套件管理員」安裝 SharpZipLib,通過在 NuGet 套件管理器的搜索欄中搜索 sharpziplib,然後選擇項目並點擊「安裝」按鈕。

  3. 從搜索結果中選擇 "SharpZipLib" 並點擊 "Install" 按鈕。

  4. NuGet 會自動下載並添加必要的依賴項到您的專案中。

範例程式碼

以下是一個簡化的示例,說明如何使用 SharpZipLib 壓縮和解壓文件:

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
namespace SharpZipLibExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceDirectory = @"C:\SourceDirectory";
            string zipFilePath = @"C:\OutputDirectory\compressed.zip";
            // Compress files
            CompressDirectory(sourceDirectory, zipFilePath);
            Console.WriteLine("Files compressed successfully.");
            string extractPath = @"C:\OutputDirectory\extracted";
            // Decompress files
            Decompress(zipFilePath, extractPath);
            Console.WriteLine("Files decompressed successfully.");
        }
        static void CompressDirectory(string sourceDirectory, string zipFilePath)
        {
            using (var zipOutputStream = new ZipOutputStream(File.Create(zipFilePath)))
            {
                zipOutputStream.SetLevel(5); // Compression level (0-9)
                // Recursively add files in the source directory to the ZIP file
                AddDirectoryFilesToZip(sourceDirectory, zipOutputStream);
                zipOutputStream.Finish();
                zipOutputStream.Close();
            }
        }
        static void AddDirectoryFilesToZip(string sourceDirectory, ZipOutputStream zipOutputStream)
        {
            string[] files = Directory.GetFiles(sourceDirectory);
            foreach (string file in files)
            {
                var entry = new ZipEntry(Path.GetFileName(file));
                zipOutputStream.PutNextEntry(entry);
                using (var fileStream = File.OpenRead(file))
                {
                    byte[] buffer = new byte[4096];
                    int sourceBytes;
                    while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zipOutputStream.Write(buffer, 0, sourceBytes);
                    }
                }
            }
            string[] subdirectories = Directory.GetDirectories(sourceDirectory);
            foreach (string subdirectory in subdirectories)
            {
                AddDirectoryFilesToZip(subdirectory, zipOutputStream);
            }
        }
        static void Decompress(string zipFilePath, string extractPath)
        {
            using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry entry;
                while ((entry = zipInputStream.GetNextEntry()) != null)
                {
                    string entryPath = Path.Combine(extractPath, entry.Name);
                    if (entry.IsFile)
                    {
                        string directoryName = Path.GetDirectoryName(entryPath);
                        if (!Directory.Exists(directoryName))
                            Directory.CreateDirectory(directoryName);
                        using (var fileStream = File.Create(entryPath))
                        {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStream.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                    else if (entry.IsDirectory)
                    {
                        Directory.CreateDirectory(entryPath);
                    }
                }
            }
        }
    }
}
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
namespace SharpZipLibExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceDirectory = @"C:\SourceDirectory";
            string zipFilePath = @"C:\OutputDirectory\compressed.zip";
            // Compress files
            CompressDirectory(sourceDirectory, zipFilePath);
            Console.WriteLine("Files compressed successfully.");
            string extractPath = @"C:\OutputDirectory\extracted";
            // Decompress files
            Decompress(zipFilePath, extractPath);
            Console.WriteLine("Files decompressed successfully.");
        }
        static void CompressDirectory(string sourceDirectory, string zipFilePath)
        {
            using (var zipOutputStream = new ZipOutputStream(File.Create(zipFilePath)))
            {
                zipOutputStream.SetLevel(5); // Compression level (0-9)
                // Recursively add files in the source directory to the ZIP file
                AddDirectoryFilesToZip(sourceDirectory, zipOutputStream);
                zipOutputStream.Finish();
                zipOutputStream.Close();
            }
        }
        static void AddDirectoryFilesToZip(string sourceDirectory, ZipOutputStream zipOutputStream)
        {
            string[] files = Directory.GetFiles(sourceDirectory);
            foreach (string file in files)
            {
                var entry = new ZipEntry(Path.GetFileName(file));
                zipOutputStream.PutNextEntry(entry);
                using (var fileStream = File.OpenRead(file))
                {
                    byte[] buffer = new byte[4096];
                    int sourceBytes;
                    while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zipOutputStream.Write(buffer, 0, sourceBytes);
                    }
                }
            }
            string[] subdirectories = Directory.GetDirectories(sourceDirectory);
            foreach (string subdirectory in subdirectories)
            {
                AddDirectoryFilesToZip(subdirectory, zipOutputStream);
            }
        }
        static void Decompress(string zipFilePath, string extractPath)
        {
            using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry entry;
                while ((entry = zipInputStream.GetNextEntry()) != null)
                {
                    string entryPath = Path.Combine(extractPath, entry.Name);
                    if (entry.IsFile)
                    {
                        string directoryName = Path.GetDirectoryName(entryPath);
                        if (!Directory.Exists(directoryName))
                            Directory.CreateDirectory(directoryName);
                        using (var fileStream = File.Create(entryPath))
                        {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStream.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                    else if (entry.IsDirectory)
                    {
                        Directory.CreateDirectory(entryPath);
                    }
                }
            }
        }
    }
}
Imports ICSharpCode.SharpZipLib.Zip
Imports System
Imports System.IO
Namespace SharpZipLibExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim sourceDirectory As String = "C:\SourceDirectory"
			Dim zipFilePath As String = "C:\OutputDirectory\compressed.zip"
			' Compress files
			CompressDirectory(sourceDirectory, zipFilePath)
			Console.WriteLine("Files compressed successfully.")
			Dim extractPath As String = "C:\OutputDirectory\extracted"
			' Decompress files
			Decompress(zipFilePath, extractPath)
			Console.WriteLine("Files decompressed successfully.")
		End Sub
		Private Shared Sub CompressDirectory(ByVal sourceDirectory As String, ByVal zipFilePath As String)
			Using zipOutputStream As New ZipOutputStream(File.Create(zipFilePath))
				zipOutputStream.SetLevel(5) ' Compression level (0-9)
				' Recursively add files in the source directory to the ZIP file
				AddDirectoryFilesToZip(sourceDirectory, zipOutputStream)
				zipOutputStream.Finish()
				zipOutputStream.Close()
			End Using
		End Sub
		Private Shared Sub AddDirectoryFilesToZip(ByVal sourceDirectory As String, ByVal zipOutputStream As ZipOutputStream)
			Dim files() As String = Directory.GetFiles(sourceDirectory)
			For Each file As String In files
				Dim entry = New ZipEntry(Path.GetFileName(file))
				zipOutputStream.PutNextEntry(entry)
				Using fileStream = System.IO.File.OpenRead(file)
					Dim buffer(4095) As Byte
					Dim sourceBytes As Integer
					sourceBytes = fileStream.Read(buffer, 0, buffer.Length)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
					Do While sourceBytes > 0
						zipOutputStream.Write(buffer, 0, sourceBytes)
						sourceBytes = fileStream.Read(buffer, 0, buffer.Length)
					Loop
				End Using
			Next file
			Dim subdirectories() As String = Directory.GetDirectories(sourceDirectory)
			For Each subdirectory As String In subdirectories
				AddDirectoryFilesToZip(subdirectory, zipOutputStream)
			Next subdirectory
		End Sub
		Private Shared Sub Decompress(ByVal zipFilePath As String, ByVal extractPath As String)
			Using zipInputStream As New ZipInputStream(File.OpenRead(zipFilePath))
				Dim entry As ZipEntry
				entry = zipInputStream.GetNextEntry()
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: while ((entry = zipInputStream.GetNextEntry()) != null)
				Do While entry IsNot Nothing
					Dim entryPath As String = Path.Combine(extractPath, entry.Name)
					If entry.IsFile Then
						Dim directoryName As String = Path.GetDirectoryName(entryPath)
						If Not Directory.Exists(directoryName) Then
							Directory.CreateDirectory(directoryName)
						End If
						Using fileStream = File.Create(entryPath)
							Dim buffer(4095) As Byte
							Dim bytesRead As Integer
							bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
							Do While bytesRead > 0
								fileStream.Write(buffer, 0, bytesRead)
								bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)
							Loop
						End Using
					ElseIf entry.IsDirectory Then
						Directory.CreateDirectory(entryPath)
					End If
					entry = zipInputStream.GetNextEntry()
				Loop
			End Using
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

SharpZipLib 長期以來一直是 .NET 語言開發社群中的主力,提供處理壓縮檔案(如 ZIP、GZip、Tar 和 BZip2)所需的基本功能。然而,隨著技術的不斷演進以及開發者尋求更先進的解決方案,SharpZipLib 的某些限制變得顯而易見。

SharpZipLib的限制

  1. 複雜性:SharpZipLib 的 API 可能繁瑣且冗長,要求開發人員撰寫大量程式碼來執行創建或提取 ZIP 存檔等簡單任務。

  2. 缺乏現代功能:SharpZipLib 不支持現代 .NET 功能和平台,這使得其不太適合當代開發環境。

  3. 有限的文件:雖然 SharpZipLib 已存在很長一段時間,但其文件往往稀少且過時,使得開發者難以入門或解決問題。

  4. 性能:SharpZipLib 的性能可能無法始終滿足開發人員的期望,特別是在處理大型或複雜的壓縮檔時。

IronZIP: 彌合差距

IronZIP 文檔,由Iron Software 總覽開發,是一個現代且高效的解決方案,用於管理 .NET 應用程式中的 ZIP 檔案。 憑藉其直觀的 API,開發人員可以輕鬆創建、閱讀和操作 ZIP 文件。 IronZIP 提供進階功能,如可自訂的壓縮等級和密碼保護,確保靈活性和資料安全。 兼容最新的 .NET 版本,IronZIP 經過性能優化,可輕鬆高效地簡化檔案管理任務。

Sharpziplib 解壓 ZIP C# (開發人員如何運作): 圖 4 - IronZIP for .NET: C# 記錄檔案壓縮庫

IronZIP 功能 是一個強大且現代化的解決方案,能克服 SharpZipLib 的不足。 以下是 IronZIP 如何填補空白:

  1. 進階 API:IronZIP 提供直覺且開發者友好的 API,簡化了檔案管理任務。 使用 IronZIP,開發人員只需撰寫少量代碼即可完成複雜操作,從而減少開發時間和精力。

  2. 完整的 .NET 支援:IronZIP 完全支援最新的 .NET 版本,包括 .NET Core、.NET Standard 和 .NET Framework,確保其與現代開發環境和平台的相容性。

  3. 全面文件:IronZIP 附帶全面的文件和範例,使開發人員能迅速掌握其功能和能力。 廣泛的文件有助於簡化學習曲線,促進在專案中的快速整合。

  4. 壓縮等級控制:IronZIP 為開發者提供了對壓縮等級的控制,允許他們根據需求調整壓縮等級。 此功能使開發人員能夠在減少文件大小與壓縮速度之間取得平衡。

  5. 密碼保護:IronZIP 支援壓縮檔案的密碼保護,提升敏感資料的安全性。 開發人員可以輕鬆使用傳統、AES128 和 AES256 密碼對 ZIP 壓縮檔進行加密,確保只有授權用戶能訪問壓縮檔的內容。

  6. 性能優化:IronZIP 經過性能優化,比 SharpZipLib 提供更快的壓縮和解壓速度。 此優化確保開發人員能夠高效處理大量數據,而不會影響效能。

    探索IronZIP 文件以獲取有關如何開始使用 IronZIP 的更多信息。IronZIP 代碼示例可幫助你輕鬆開始。

IronZIP 安裝

以下是將XDocument與IronPDF整合的步驟:

  • 開啟Visual Studio IDE或您偏好的 IDE。
  • 從工具選單中,導航到 NuGet 套件管理器主控台。
  • 運行以下命令以安裝 IronZIP 套件:
  Install-Package IronZip
  Install-Package IronZip
SHELL
  • 或者,您可以從 NuGet 套件管理器為解決方案安裝它。
  • 從 NuGet 瀏覽標籤中選擇 IronZIP,然後點擊安裝:

    Sharpziplib 解壓縮 ZIP C# (給開發人員的工作原理):圖 5 - 使用 NuGet 套件管理器的解決方案管理 NuGet 套件安裝 IronZIP,通過在搜索欄中搜索 IronZip,然後選擇專案並單擊安裝按鈕。

範例程式碼

以下源代碼展示了如何使用IronZIP高效地創建ZIP文件,輕鬆實現且僅需幾行代碼。 在這裡,您可以通過在指定的資料夾中提供檔名,將多個檔案添加到受密碼保護的 ZIP 檔案中。 在建立IronZipArchive物件時,您也可以指定壓縮等級以減少輸出檔案的空間大小。

using IronZip;
using IronZip.Enum;
class Program
{
    static void Main()
    {
        // Create an empty ZIP with the highest compression
        using (var archive = new IronZipArchive(9))
        {
            // Password protect the ZIP (Support AES128 & AES256)
            archive.SetPassword("P@ssw0rd", EncryptionMethods.Traditional);
            archive.AddArchiveEntry("./assets/file1.txt");
            archive.AddArchiveEntry("./assets/file2.txt");
            // Export the ZIP
            archive.SaveAs("output.zip");
        }
    }
}
using IronZip;
using IronZip.Enum;
class Program
{
    static void Main()
    {
        // Create an empty ZIP with the highest compression
        using (var archive = new IronZipArchive(9))
        {
            // Password protect the ZIP (Support AES128 & AES256)
            archive.SetPassword("P@ssw0rd", EncryptionMethods.Traditional);
            archive.AddArchiveEntry("./assets/file1.txt");
            archive.AddArchiveEntry("./assets/file2.txt");
            // Export the ZIP
            archive.SaveAs("output.zip");
        }
    }
}
Imports IronZip
Imports IronZip.Enum
Friend Class Program
	Shared Sub Main()
		' Create an empty ZIP with the highest compression
		Using archive = New IronZipArchive(9)
			' Password protect the ZIP (Support AES128 & AES256)
			archive.SetPassword("P@ssw0rd", EncryptionMethods.Traditional)
			archive.AddArchiveEntry("./assets/file1.txt")
			archive.AddArchiveEntry("./assets/file2.txt")
			' Export the ZIP
			archive.SaveAs("output.zip")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出 Zip 檔案

Sharpziplib 解壓縮 C#(開發人員如何使用):圖 6 - 輸出:使用 IronZIP 創建的受密碼保護的 Zip 壓縮檔。

結論

SharpZipLib 概述成為一個強大的 .NET 壓縮庫,提供豐富的功能和能力,有效處理壓縮文件。 無論是壓縮數據以進行儲存、存檔文件,還是在網路服務中優化帶寬使用,SharpZipLib 提供了必要的工具來簡化壓縮和解壓縮的操作。 由於其開源性、跨平台相容性和強大的功能,SharpZipLib 仍然是開發人員在 .NET 應用程式中尋求可靠壓縮解決方案的首選。

儘管SharpZipLib一直是處理.NET應用程式中壓縮檔案的可靠選擇,但在當今的開發環境中,其限制變得越來越明顯。 探索IronZIP API 彌補了SharpZipLib留下的空白,提供了一個現代且功能豐富的替代方案,優先考慮使用的便利性、性能和相容性。 使用 IronZIP,開發者可以在檔案管理中開啟新的可能性,並通過先進的功能和直觀的 API 簡化其開發工作流程。

IronZIP 提供免費試用授權概覽。 從IronZIP 下載下載程式庫並試用。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Xceed.Document .NET(開發人員如何使用)
下一個 >
Xdocument C#(其運作方式對於開發者)