.NET幫助 Sharpziplib 提取 ZIP C#(對於開發者的運行原理) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article In today's digital landscape, where data management is paramount, having efficient tools for compression and decompression is crucial. One such tool that stands out in the .NET ecosystem is SharpZipLib. In this article, we'll take a deep dig at SharpZipLib, exploring its features, applications, and how to integrate it into your .NET projects. What is SharpZipLib? SharpZipLib is a feature-rich, open-source compression library for .NET, written entirely in C#. It provides comprehensive support for various compression formats, including ZIP, GZip, and Tar. Developed by a dedicated community, SharpZipLib offers a wide range of functionalities for compressing and decompressing files efficiently. Features and Capabilities Support for Multiple Compression Formats: SharpZipLib supports popular compression formats like ZIP, GZip, and Tar, catering to diverse use cases and requirements. Stream-Based Operations: The library operates on streams, enabling developers to work with data from various sources, including files, memory streams, or network streams. This flexibility facilitates seamless integration into different parts of an application. Compression Levels: Developers can fine-tune compression levels to balance between compression ratio and processing speed, based on their specific needs. Password Protection: SharpZipLib allows the creation of password-protected ZIP archives, ensuring data security by encrypting contents with a specified password. Error Handling and Recovery: Robust error handling mechanisms enable developers to gracefully handle exceptions during compression and decompression operations. Additionally, SharpZipLib supports recovery from corrupt archives, enhancing reliability. Use Cases File Compression and Archiving: SharpZipLib is ideal for applications that require compressing and archiving files, such as backup utilities, file management tools, or data export functionalities. Web Services and APIs: Web services dealing with file transfers or data exchange often benefit from compression to reduce bandwidth usage. SharpZipLib can be seamlessly integrated into such services to compress outgoing data or decompress incoming payloads efficiently. Desktop Applications: Desktop applications dealing with large datasets or resource files can leverage SharpZipLib to compress files for storage or distribution. This is particularly useful for software installers or data synchronization tools. Data Backup and Storage: Applications requiring periodic backups or storage of data in compressed format can automate the backup process and conserve storage space effectively using SharpZipLib. Advantages of SharpZipLib Open Source: As an open-source library, SharpZipLib encourages collaboration and community contributions, ensuring continuous improvement and adaptability to evolving needs. Cross-Platform Compatibility: SharpZipLib, being written in C# and targeting the .NET framework, is compatible with various platforms, including Windows, Linux, and macOS, enhancing its versatility. Lightweight and Efficient: SharpZipLib is designed to be lightweight and efficient, minimizing resource consumption while delivering high-performance compression and decompression capabilities. Extensive Documentation and Support: Comprehensive documentation and community support make it easier for developers to integrate and troubleshoot issues when using SharpZipLib. Create C# Visual Studio Project Open Visual Studio and click on the "Create a new project" option. Choose the appropriate project template based on your requirements (e.g., Console Application, Windows Forms Application). Specify the project name and location, then click "Next". From Additional Information, select the latest .NET Framework. Click "Create" to create the project. Installation Process To integrate SharpZipLib into your .NET project: In your Visual Studio IDE C# ConsoleApp, right-click on your project in Solution Explorer and select "Manage NuGet Packages..." In the NuGet Package Manager window, search for "SharpZipLib". Select "SharpZipLib" from the search results and click on the "Install" button. NuGet will download and add the necessary dependencies to your project automatically. 代碼示例 Here's a simplified example demonstrating how to use SharpZipLib to compress and decompress files: using ICSharpCode.SharpZipLib.Zip; using System; using System.IO; namespace SharpZipLibExample { class Program { static void Main(string[] args) { string sourceDirectory = @"C:\SourceDirectory"; // Source directory containing files to compress string zipFilePath = @"C:\OutputDirectory\compressed.zip"; // Output path for the compressed ZIP file // Compress files from the source directory CompressDirectory(sourceDirectory, zipFilePath); Console.WriteLine("Files compressed successfully."); string extractPath = @"C:\OutputDirectory\extracted"; // Path to extract the decompressed files // Decompress files from the ZIP archive Decompress(zipFilePath, extractPath); Console.WriteLine("Files decompressed successfully."); } // Method to compress all files in a directory to a ZIP file static void CompressDirectory(string sourceDirectory, string zipFilePath) { using (var zipOutputStream = new ZipOutputStream(File.Create(zipFilePath))) { zipOutputStream.SetLevel(5); // Set compression level (0-9), 5 as a mid-range // Recursively add files in the source directory to the ZIP file AddDirectoryFilesToZip(sourceDirectory, zipOutputStream); zipOutputStream.Finish(); zipOutputStream.Close(); } } // Method to add files from a directory to a ZIP output stream static void AddDirectoryFilesToZip(string sourceDirectory, ZipOutputStream zipOutputStream) { // Get list of files in the directory string[] files = Directory.GetFiles(sourceDirectory); foreach (string file in files) { var entry = new ZipEntry(Path.GetFileName(file)); // Create a new entry for each file zipOutputStream.PutNextEntry(entry); using (var fileStream = File.OpenRead(file)) { // Buffer for reading files byte[] buffer = new byte[4096]; int sourceBytes; // Read file and write to ZIP stream while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0) { zipOutputStream.Write(buffer, 0, sourceBytes); } } } // Handle subdirectories recursively string[] subdirectories = Directory.GetDirectories(sourceDirectory); foreach (string subdirectory in subdirectories) { AddDirectoryFilesToZip(subdirectory, zipOutputStream); } } // Method to decompress files from a ZIP file static void Decompress(string zipFilePath, string extractPath) { using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry entry; // Read entries from the ZIP archive while ((entry = zipInputStream.GetNextEntry()) != null) { string entryPath = Path.Combine(extractPath, entry.Name); // Process files if (entry.IsFile) { string directoryName = Path.GetDirectoryName(entryPath); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); using (var fileStream = File.Create(entryPath)) { // Buffer for reading entries byte[] buffer = new byte[4096]; int bytesRead; // Read from ZIP stream and write to file while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, bytesRead); } } } else if (entry.IsDirectory) // Process directories { 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"; // Source directory containing files to compress string zipFilePath = @"C:\OutputDirectory\compressed.zip"; // Output path for the compressed ZIP file // Compress files from the source directory CompressDirectory(sourceDirectory, zipFilePath); Console.WriteLine("Files compressed successfully."); string extractPath = @"C:\OutputDirectory\extracted"; // Path to extract the decompressed files // Decompress files from the ZIP archive Decompress(zipFilePath, extractPath); Console.WriteLine("Files decompressed successfully."); } // Method to compress all files in a directory to a ZIP file static void CompressDirectory(string sourceDirectory, string zipFilePath) { using (var zipOutputStream = new ZipOutputStream(File.Create(zipFilePath))) { zipOutputStream.SetLevel(5); // Set compression level (0-9), 5 as a mid-range // Recursively add files in the source directory to the ZIP file AddDirectoryFilesToZip(sourceDirectory, zipOutputStream); zipOutputStream.Finish(); zipOutputStream.Close(); } } // Method to add files from a directory to a ZIP output stream static void AddDirectoryFilesToZip(string sourceDirectory, ZipOutputStream zipOutputStream) { // Get list of files in the directory string[] files = Directory.GetFiles(sourceDirectory); foreach (string file in files) { var entry = new ZipEntry(Path.GetFileName(file)); // Create a new entry for each file zipOutputStream.PutNextEntry(entry); using (var fileStream = File.OpenRead(file)) { // Buffer for reading files byte[] buffer = new byte[4096]; int sourceBytes; // Read file and write to ZIP stream while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0) { zipOutputStream.Write(buffer, 0, sourceBytes); } } } // Handle subdirectories recursively string[] subdirectories = Directory.GetDirectories(sourceDirectory); foreach (string subdirectory in subdirectories) { AddDirectoryFilesToZip(subdirectory, zipOutputStream); } } // Method to decompress files from a ZIP file static void Decompress(string zipFilePath, string extractPath) { using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry entry; // Read entries from the ZIP archive while ((entry = zipInputStream.GetNextEntry()) != null) { string entryPath = Path.Combine(extractPath, entry.Name); // Process files if (entry.IsFile) { string directoryName = Path.GetDirectoryName(entryPath); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); using (var fileStream = File.Create(entryPath)) { // Buffer for reading entries byte[] buffer = new byte[4096]; int bytesRead; // Read from ZIP stream and write to file while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, bytesRead); } } } else if (entry.IsDirectory) // Process directories { 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" ' Source directory containing files to compress Dim zipFilePath As String = "C:\OutputDirectory\compressed.zip" ' Output path for the compressed ZIP file ' Compress files from the source directory CompressDirectory(sourceDirectory, zipFilePath) Console.WriteLine("Files compressed successfully.") Dim extractPath As String = "C:\OutputDirectory\extracted" ' Path to extract the decompressed files ' Decompress files from the ZIP archive Decompress(zipFilePath, extractPath) Console.WriteLine("Files decompressed successfully.") End Sub ' Method to compress all files in a directory to a ZIP file Private Shared Sub CompressDirectory(ByVal sourceDirectory As String, ByVal zipFilePath As String) Using zipOutputStream As New ZipOutputStream(File.Create(zipFilePath)) zipOutputStream.SetLevel(5) ' Set compression level (0-9), 5 as a mid-range ' Recursively add files in the source directory to the ZIP file AddDirectoryFilesToZip(sourceDirectory, zipOutputStream) zipOutputStream.Finish() zipOutputStream.Close() End Using End Sub ' Method to add files from a directory to a ZIP output stream Private Shared Sub AddDirectoryFilesToZip(ByVal sourceDirectory As String, ByVal zipOutputStream As ZipOutputStream) ' Get list of files in the directory Dim files() As String = Directory.GetFiles(sourceDirectory) For Each file As String In files Dim entry = New ZipEntry(Path.GetFileName(file)) ' Create a new entry for each file zipOutputStream.PutNextEntry(entry) Using fileStream = System.IO.File.OpenRead(file) ' Buffer for reading files Dim buffer(4095) As Byte Dim sourceBytes As Integer ' Read file and write to ZIP stream 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 ' Handle subdirectories recursively Dim subdirectories() As String = Directory.GetDirectories(sourceDirectory) For Each subdirectory As String In subdirectories AddDirectoryFilesToZip(subdirectory, zipOutputStream) Next subdirectory End Sub ' Method to decompress files from a ZIP file Private Shared Sub Decompress(ByVal zipFilePath As String, ByVal extractPath As String) Using zipInputStream As New ZipInputStream(File.OpenRead(zipFilePath)) Dim entry As ZipEntry ' Read entries from the ZIP archive 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) ' Process files 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) ' Buffer for reading entries Dim buffer(4095) As Byte Dim bytesRead As Integer ' Read from ZIP stream and write to file 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 ' Process directories Directory.CreateDirectory(entryPath) End If entry = zipInputStream.GetNextEntry() Loop End Using End Sub End Class End Namespace $vbLabelText $csharpLabel SharpZipLib has long been a staple in the .NET language development community, providing essential functionality for working with compressed archives such as ZIP, GZip, Tar, and BZip2. However, as technology evolves and developers seek more advanced solutions, certain limitations of SharpZipLib have become apparent. Limitations of SharpZipLib Complexity: SharpZipLib's API can be cumbersome and verbose, requiring developers to write lengthy code to perform simple tasks such as creating or extracting ZIP archives. Lack of Modern Features: SharpZipLib lacks support for modern .NET features and platforms, making it less suitable for contemporary development environments. Limited Documentation: While SharpZipLib has been around for a long time, its documentation is often sparse and outdated, making it challenging for developers to get started or troubleshoot issues. Performance: SharpZipLib's performance may not always meet the expectations of developers, especially when dealing with large or complex archives. IronZIP: Bridging the Gap IronZIP Documentation, developed by Iron Software Overview, is a modern and efficient solution for managing ZIP archives in .NET applications. With its intuitive API, developers can easily create, read, and manipulate ZIP files. IronZIP offers advanced features like customizable compression levels and password protection, ensuring flexibility and data security. Compatible with the latest .NET versions and optimized for performance, IronZIP streamlines archive management tasks with ease and efficiency. IronZIP Features emerges as a robust and modern solution that addresses the shortcomings of SharpZipLib. Here's how IronZIP fills the gaps: Advanced API: IronZIP offers an intuitive and developer-friendly API that simplifies archive management tasks. With IronZIP, developers can accomplish complex operations with just a few lines of code, reducing development time and effort. Full .NET Support: IronZIP fully supports the latest .NET versions, including .NET Core, .NET Standard, and .NET Framework, ensuring compatibility with modern development environments and platforms. Comprehensive Documentation: IronZIP comes with comprehensive documentation and examples, empowering developers to quickly grasp its features and capabilities. The extensive documentation helps streamline the learning curve and facilitates rapid integration into projects. Compression Level Control: IronZIP provides developers with control over the compression level, allowing them to adjust the level of compression based on their requirements. This feature enables developers to balance between file size reduction and compression speed. Password Protection: IronZIP supports password protection for ZIP archives, enhancing security for sensitive data. Developers can easily encrypt ZIP archives with traditional, AES128, and AES256 passwords, ensuring that only authorized users can access the contents of the archive. Performance Optimization: IronZIP is optimized for performance, delivering faster compression and extraction speeds compared to SharpZipLib. This optimization ensures that developers can efficiently handle large volumes of data without compromising on performance. Explore IronZIP Documentation for more information on getting started with IronZIP. The IronZIP Code Examples help you to start without any hassle. IronZIP Installation Here are the steps to integrate XDocument with IronPDF: Open Visual Studio IDE or your preferred IDE. From the Tools menu, navigate to the NuGet Package Manager Console. Run the following command to install the IronZIP package: Install-Package IronPdf Alternatively, you can install it from NuGet Package Manager for Solutions. Select IronZIP from NuGet browse tab and click install: 代碼示例 The following source code shows how IronZIP efficiently creates a ZIP file with IronZIP with ease and with just a few lines of code. Here, you can add multiple files to the password-protected ZIP archive by providing the filenames in the specified folder. While creating the IronZipArchive object you can also specify the compression level to reduce the space size of the output file. 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 Output Zip File 結論 SharpZipLib Overview emerges as a powerful compression library for .NET, offering a rich set of features and capabilities for handling compressed files efficiently. Whether it's compressing data for storage, archiving files, or optimizing bandwidth usage in web services, SharpZipLib provides the necessary tools to streamline compression and decompression operations. With its open-source nature, cross-platform compatibility, and robust functionality, SharpZipLib remains a top choice for developers seeking a reliable solution for compression tasks in their .NET applications. While SharpZipLib has been a reliable choice for working with compressed archives in .NET applications, its limitations have become increasingly apparent in today's development landscape. Explore IronZIP API steps in to fill the gaps left by SharpZipLib, offering a modern and feature-rich alternative that prioritizes ease of use, performance, and compatibility. With IronZIP, developers can unlock new possibilities in archive management and streamline their development workflow with advanced capabilities and intuitive API. IronZIP provides a free trial licensing overview. Download the library from IronZIP Downloads and give it a try. 常見問題解答 如何在C#中使用SharpZipLib解壓ZIP檔案? 要在C#中使用SharpZipLib解壓ZIP檔案,您可以使用FastZip類,它提供了提取ZIP存檔的方法。您可以初始化FastZip的新實例,並使用ExtractZip方法,指定來源和目標路徑。 SharpZipLib for .NET的常見特性有哪些? SharpZipLib支持多種壓縮格式,如ZIP、GZip和Tar。它允許基於流的操作、可調整的壓縮級別,並包括密碼保護以確保ZIP存檔的安全。 如何在.NET應用程序中提高壓縮性能? IronZIP為壓縮任務提供了優化的性能。它提供直觀的API、可自定義的壓縮級別,並支持最新的.NET版本,實現高效管理ZIP檔案。 使用較舊的壓縮庫如SharpZipLib有哪些挑戰? 一些挑戰包括繁瑣的API、缺乏現代功能、有限的文檔,以及處理大型存檔時的潛在性能問題。 IronZIP如何提升.NET壓縮任務的工作效率? IronZIP通過提供進階特性如可自定義的壓縮、密碼保護和直觀的API提升工作效率。它還提供全面的文檔,並支持最新的.NET版本以實現無縫整合。 我可以在C#中使用SharpZipLib用密碼保護ZIP檔案嗎? 可以,SharpZipLib允許您用密碼保護ZIP檔案。您可以使用ZipOutputStream並設置Password屬性為ZIP檔案指定密碼。 IronZIP作為SharpZipLib的現代替代方案有何特點? IronZIP提供一個現代的替代方案,具有直觀的API、全面的文檔、對最新.NET版本的完整支持、密碼保護及優化的性能等特點。 如何在我的.NET專案中安裝SharpZipLib? 您可以通過Visual Studio中的NuGet包管理器安裝SharpZipLib。搜索'SharpZipLib'並安裝以整合到您的.NET專案中。 使用IronZIP比傳統庫有哪些優勢? IronZIP提供如直觀的API、增強的性能、對現代.NET框架的支持、可自定義的壓縮級別及強大的密碼保護等優勢。 在哪裡可以找到SharpZipLib的資源和文檔? SharpZipLib的文檔和資源可以在其官方NuGet頁面和GitHub庫找到,提供整合和使用的指南和示例。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Xceed.Document .NET(對於開發者的運行原理)Xdocument C#(對於開發者的...