跳過到頁腳內容
.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窗體應用)。

    Sharpziplib Extract ZIP C# (How It Works For Developers): Figure 1 - For the new project, select a Console App in C#.

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

    Sharpziplib解壓ZIP C#(開發者操作指南):圖2 - 配置您的專案,指定專案名稱、位置和解決方案名稱。 接下來,選擇.NET框架並單擊創建。

  4. 從其他信息中選擇最新的.NET框架。 單擊"創建"來創建專案。

安裝過程

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

  1. 在您的Visual Studio IDE C# ConsoleApp中,在Solution Explorer中右鍵單擊專案,然後選擇"管理NuGet套件..."
  2. 在NuGet套件管理器窗口中,搜尋"SharpZipLib"。

    Sharpziplib Extract ZIP C# (How It Works For Developers): Figure 3 - Install SharpZipLib using the Manage NuGet Package for Solution by searching sharpziplib in the search bar of NuGet Package Manager, then select the project and click on the Install button.

  3. 從搜尋結果中選擇"SharpZipLib"並按"安裝"按鈕。
  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";     // 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);
                    }
                }
            }
        }
    }
}
$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# Zip Archive Library

IronZIP特徵作為一個強大而現代的解決方案出現,解決了SharpZipLib的不足。 以下是IronZIP如何填補這些空白:

  1. 先進的API:IronZIP提供了一個直觀且對開發者友好的API,簡化了檔案管理任務。 使用IronZIP,開發者可以僅用幾行代碼完成複雜的操作,減少開發時間和精力。
  2. 完全的.NET支持:IronZIP完全支持最新的.NET版本,包括.NET Core、.NET Standard和.NET Framework,確保與現代開發環境和平台的兼容性。
  3. 全面的文檔:IronZIP配有全面的文檔和示例,使開發者能夠快速掌握其功能和能力。 廣泛的文檔有助於簡化學習曲線並促進快速整合到專案中。
  4. 壓縮等級控制:IronZIP提供了對壓縮等級的控制,使開發者可以根據需求調整壓縮等級。 此功能使開發者能夠在文件大小減少和壓縮速度之間取得平衡。
  5. 密碼保護:IronZIP支持ZIP檔案的密碼保護,增強敏感資料的安全性。 開發者可以輕鬆使用傳統、AES128和AES256密碼加密ZIP檔案,確保只有授權使用者才能訪問檔案內容。
  6. 性能優化:IronZIP經過性能優化,提供比SharpZipLib更快的壓縮和提取速度。 這種優化確保開發者能夠高效地處理大量數據而不會影響性能。

探索IronZIP文檔以獲取有關入門的信息。IronZIP程式碼示例幫助您輕鬆開始。

IronZIP安裝

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

  • 打開Visual Studio IDE或您偏好的IDE。
  • 從工具菜單中,導航到NuGet套件管理控制台。
  • 運行以下命令來安裝IronZIP套件:

    Install-Package IronPdf
  • 替代方法是,您可以從解決方案的NuGet套件管理器中安裝它。
  • 從NuGet瀏覽選項卡中選擇IronZIP並單擊安裝:

Sharpziplib Extract ZIP C# (How It Works For Developers): Figure 5 - Install IronZIP using the Manage NuGet Package for Solution by searching IronZip in the search bar of NuGet Package Manager, then select the project and click on the Install button.

程式碼示例

以下源代碼顯示瞭如何使用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");
        }
    }
}
$vbLabelText   $csharpLabel

輸出Zip文件

Sharpziplib解壓ZIP C#(開發者操作指南):圖6 - 使用IronZIP創建的密碼保護的Zip檔案

結論

SharpZipLib概覽作為一個強大的.NET壓縮程式庫出現,提供了一整套豐富的功能和能力,以有效地處理壓縮文件。 無論是壓縮用於存儲的數據、檔案保存、或在網絡服務中優化帶寬使用,SharpZipLib都提供了簡化壓縮和解壓縮操作所需的工具。 憑藉其開源特性、跨平台兼容性和強大的功能,SharpZipLib仍然是尋求可靠壓縮任務解決方案的開發者的首選。

儘管SharpZipLib一直是.NET應用中處理壓縮存檔的可靠選擇,但在當前的開發環境中,其局限性日益顯現。 探索IronZIP API填補了SharpZipLib留下的空白,提供了一個現代且功能豐富的替代方案,優先考慮易用性、性能和兼容性。 使用IronZIP,開發者可以在檔案管理中解鎖新的可能性,並通過先進的功能和直觀的API簡化開發流程。

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

常見問題解答

如何在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庫找到,提供整合和使用的指南和示例。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me