跳過到頁腳內容
使用 IRONZIP

如何在 C# 中提取 Zip 文件

Zip files are a popular method for compressing multiple files or directories into a single Zip archive format, and extracting them is a fundamental operation in many software applications. In the world of C#, working with Zip archives is easy with the IronZip namespace. This article will explore how to extract Zip files using C# and examine the available tools and techniques.

In the file system, where the organization and storage of data are paramount, the ability to unzip files seamlessly becomes a critical skill. Using the system effectively to manage all the files within a specified directory is essential for streamlined operations. One powerful tool in this context is the ZipArchive class, a robust feature in C# that facilitates efficient extraction of zipped files. This article will guide you through the intricacies of leveraging the ZipArchive class, shedding light on essential concepts such as local file headers of zipped files.

Prerequisites

Before you explore ZIP file manipulation with IronZIP and IronPDF, ensure the following prerequisites are met:

  1. Visual Studio: Install Visual Studio or any other C# Integrated Development Environment (IDE) of your choice.
  2. Basic C# knowledge: Familiarize yourself with fundamental concepts of the C# programming language.

Install IronZIP Package

To start your journey with IronZIP, swiftly install the IronZIP NuGet Package in your project. Execute the following command in the NuGet Package Manager Console:

Install-Package IronZip

Alternatively, download the package directly from the official IronZIP NuGet website.

Once the installation is complete, initiate your C# code by adding the using IronZIP statement at the top.

Apply License Key

Ensure you have a valid license or trial key for IronZIP. Apply the license key by assigning it to the LicenseKey property of the License class. Include the following code immediately after the import statement and before using any IronZIP methods:

IronZIP.Licensing.License.LicenseKey = "IRONZIP.MYLICENSE.KEY.1EF01";
IronZIP.Licensing.License.LicenseKey = "IRONZIP.MYLICENSE.KEY.1EF01";
IronZIP.Licensing.License.LicenseKey = "IRONZIP.MYLICENSE.KEY.1EF01"
$vbLabelText   $csharpLabel

This step is crucial for unleashing the full potential of IronZIP in your project.

Using C# to extract or compress Zip files

The following code samples demonstrate how to work with Zip files in C#, whether you want to compress or extract a file.

Extract a Zip file using C#

The following code sample will unzip files into a new directory using IronZIP.

using IronZIP;

namespace CS_ZipArchive
{
    internal class Program
    {
        public static void Main(string[] args)
        {       
            // Extract the contents of "QRCode.zip" into the "Extracted QRCode" directory
            IronArchive.ExtractArchiveToDirectory("QRCode.zip", "Extracted QRCode");
        }
     }
}
using IronZIP;

namespace CS_ZipArchive
{
    internal class Program
    {
        public static void Main(string[] args)
        {       
            // Extract the contents of "QRCode.zip" into the "Extracted QRCode" directory
            IronArchive.ExtractArchiveToDirectory("QRCode.zip", "Extracted QRCode");
        }
     }
}
Imports IronZIP

Namespace CS_ZipArchive
	Friend Class Program
		Public Shared Sub Main(ByVal args() As String)
			' Extract the contents of "QRCode.zip" into the "Extracted QRCode" directory
			IronArchive.ExtractArchiveToDirectory("QRCode.zip", "Extracted QRCode")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

The above code uses the IronZIP library, which provides functionality for working with ZIP archives in C#. This line aims to extract the contents of a ZIP archive file named "QRCode.zip" and save them to a directory named "Extracted QRCode". The ExtractArchiveToDirectory() method is responsible for extracting the contents of a ZIP archive. It takes two arguments: the source file and the destination.

csharp-extract-zip-file-tutorial-1

Create an Archive File

To make a ZIP file in C#, we can utilize the IronArchive class found in the IronZIP namespace. This class makes creating a ZIP archive and including files within it straightforward. By employing IronArchive, developers can easily handle the task of crafting ZIP files in their C# programs, enhancing efficiency and simplifying the file management process.

using IronZIP;

namespace CS_ZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new ZIP file named "myPDFFiles.zip"
            using (var archive = new IronArchive("myPDFFiles.zip"))
            {
                // Add files to the ZIP
                archive.Add(@"E:\Files\file1.pdf");
                archive.Add(@"E:\Files\file2.pdf");
                archive.Add(@"D:\Invoices\Invoice.pdf");
            }
        }
    }
}
using IronZIP;

namespace CS_ZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new ZIP file named "myPDFFiles.zip"
            using (var archive = new IronArchive("myPDFFiles.zip"))
            {
                // Add files to the ZIP
                archive.Add(@"E:\Files\file1.pdf");
                archive.Add(@"E:\Files\file2.pdf");
                archive.Add(@"D:\Invoices\Invoice.pdf");
            }
        }
    }
}
Imports IronZIP

Namespace CS_ZipArchive
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create a new ZIP file named "myPDFFiles.zip"
			Using archive = New IronArchive("myPDFFiles.zip")
				' Add files to the ZIP
				archive.Add("E:\Files\file1.pdf")
				archive.Add("E:\Files\file2.pdf")
				archive.Add("D:\Invoices\Invoice.pdf")
			End Using
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

The using statement creates a scoped resource associated with an instance of the IronArchive class. The IronArchive constructor is called with the argument "myPDFFiles.zip", which specifies the name of the new ZIP archive to be created. Inside the using block, three lines of code add files to the newly created archive:

  • archive.Add(@"E:\Files\file1.pdf");
  • archive.Add(@"E:\Files\file2.pdf");
  • archive.Add(@"D:\Invoices\Invoice.pdf");

These lines add the specified PDF files to the "myPDFFiles.zip" archive. Since the IronArchive class implements IDisposable, the using statement ensures the archive is closed correctly, and resources are released when the code block is exited.

In this way, this program creates a ZIP archive named "myPDFFiles.zip" and adds three PDF files to it. IronZip provides methods to create and extract zip files super efficiently.

csharp-extract-zip-file-tutorial-2

Create a New Ziparchive from the Existing File System

We can create a new zip archive from a specified zip file. As shown below, we can add multiple files with different formats, such as images and PDFs.

using IronZIP;

namespace CS_ZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new ZIP file named "new PDF Files.zip" by extracting content from "myPDFFiles.zip"
            using (var archive = IronArchive.FromFile("myPDFFiles.zip", "new PDF Files.zip"))
            {
                // Add files to the archive
                archive.Add(@"D:\Invoices\Image1.png");
                archive.Add(@"D:\Invoices\PDF3.pdf");
            }
        }
    }
}
using IronZIP;

namespace CS_ZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new ZIP file named "new PDF Files.zip" by extracting content from "myPDFFiles.zip"
            using (var archive = IronArchive.FromFile("myPDFFiles.zip", "new PDF Files.zip"))
            {
                // Add files to the archive
                archive.Add(@"D:\Invoices\Image1.png");
                archive.Add(@"D:\Invoices\PDF3.pdf");
            }
        }
    }
}
Imports IronZIP

Namespace CS_ZipArchive
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create a new ZIP file named "new PDF Files.zip" by extracting content from "myPDFFiles.zip"
			Using archive = IronArchive.FromFile("myPDFFiles.zip", "new PDF Files.zip")
				' Add files to the archive
				archive.Add("D:\Invoices\Image1.png")
				archive.Add("D:\Invoices\PDF3.pdf")
			End Using
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

This C# code snippet utilizes IronArchive to create a new ZIP file named "new PDF Files.zip" by extracting content from an existing ZIP file called "myPDFFiles.zip." Inside the using block, files like "Image1.png" and "PDF3.pdf" are added to the new ZIP archive. The code efficiently extracts and adds specific files from one archive to another using IronArchive.

Compressing PDF Files in C#

In C#, you can effortlessly compress PDF files using any third-party library, and one of the most efficient tools for this task is IronPDF. Its compression algorithm empowers you to shrink the size of PDF documents while maintaining their quality.

Introducing IronPDF

IronPDF is a popular C# library that equips developers to work seamlessly with PDF files in their .NET framework applications. Beyond its compression capabilities, it offers diverse PDF generation, manipulation, conversion, and more features. This flexibility makes it an invaluable tool for various PDF-related tasks. Whether creating PDFs from scratch, converting data from HTML to PDF, or engaging in other PDF operations, IronPDF simplifies the entire process, enhancing productivity for C# developers.

Install IronPDF NuGet Package

To incorporate IronPDF into your project, execute the following command to install IronPDF.

Install-Package IronZip

This command streamlines the installation process and adds the necessary dependencies to your project, ensuring a smooth integration.

Write Code to Compress PDF File in C#

We're focusing on PDF compression in the provided C# code snippet.

using IronPdf;

public static void CompressPdf()
{
    // Open the PDF document located at D:\SamplePDFFile.pdf
    var pdf = new PdfDocument(@"D:\SamplePDFFile.pdf");

    // Compress the images in the PDF document to 60% of their original quality
    pdf.CompressImages(60);

    // Save the compressed PDF as a new file
    pdf.SaveAs(@"D:\CompressedPDF.pdf");
}
using IronPdf;

public static void CompressPdf()
{
    // Open the PDF document located at D:\SamplePDFFile.pdf
    var pdf = new PdfDocument(@"D:\SamplePDFFile.pdf");

    // Compress the images in the PDF document to 60% of their original quality
    pdf.CompressImages(60);

    // Save the compressed PDF as a new file
    pdf.SaveAs(@"D:\CompressedPDF.pdf");
}
Imports IronPdf

Public Shared Sub CompressPdf()
	' Open the PDF document located at D:\SamplePDFFile.pdf
	Dim pdf = New PdfDocument("D:\SamplePDFFile.pdf")

	' Compress the images in the PDF document to 60% of their original quality
	pdf.CompressImages(60)

	' Save the compressed PDF as a new file
	pdf.SaveAs("D:\CompressedPDF.pdf")
End Sub
$vbLabelText   $csharpLabel

In the above C# code, we have opened a PDF document named "SamplePDFFile.pdf"; its images are compressed to 60% of their original quality. The resulting compressed PDF file is then saved as "CompressedPDF.pdf" at the specified folder location.

csharp-extract-zip-file-tutorial-3

Further, you can use the System namespace (using System) since it provides essential classes and methods for basic functionalities in C# applications. Using the ZipArchive class, part of the System.IO.Compression namespace, you can deal with compressed files as it allows seamless extraction and manipulation of zipped files, ensuring efficient handling of compressed data. In the context of this PDF compression example, understanding and utilizing the System namespace and the IronPDF library demonstrate the versatility and power of C# in managing diverse file formats, like zipped files, gz files, or PDFs.

Conclusion

In conclusion, navigating the realm of zip file manipulation and PDF compression in C# becomes a seamless process with the powerful capabilities of the IronZIP and IronPDF libraries. This article has provided insights into extracting files from zip archives, creating new archives, and compressing PDF files, demonstrating these libraries' versatility and efficiency in C# development. By adhering to the outlined procedures and incorporating the IronZIP and IronPDF packages, developers can elevate their applications with streamlined file management, dynamic zip archive creation, and effective PDF compression. These libraries stand as valuable assets, empowering developers to handle complex tasks with ease and efficiency, ultimately enhancing the overall functionality of C# applications in the world of file handling and compression. The 30-day trial offered by Iron Software provides a risk-free opportunity to explore its capabilities, making it easy to determine its suitability for specific projects. You can purchase the license after exploring all the functionalities of IronZIP and IronPDF.

常見問題解答

如何使用 C# 提取 ZIP 文件?

您可以使用 C# 中的 IronZIP 庫提取 ZIP 文件。利用 ExtractArchiveToDirectory() 方法指定源 ZIP 文件和提取的目標目錄。

使用 C# 與 IronZIP 的需求是什麼?

要使用 IronZIP,您需要安裝 Visual Studio 或其他 C# IDE,對 C# 程序編寫有基本的了解,並且通過 NuGet 使用命令 Install-Package IronZip 安裝 IronZIP 庫。

如何在 C# 中創建 ZIP 存檔?

在 C# 中,您可以使用 IronZIP 庫中的 'IronArchive' 類別創建 ZIP 存檔。您可以使用 Add() 方法將文件添加到存檔中,並根據需要指定存檔名稱。

如何在 C# 專案中管理 ZIP 文件操作許可證?

在 C# 專案中使用 IronZIP 管理許可證時,導入 IronZIP 後立即將您的許可證密鑰分配到 'License' 類的 'LicenseKey' 屬性,然後使用其任何方法。

我可以使用 ZIP 庫壓縮 PDF 文件嗎?

雖然 ZIP 庫主要用於文件壓縮,但對於專業的 PDF 壓縮和操作,您應該使用 IronPDF,它提供了處理 C# 中 PDF 文件的全面功能。

使用 IronZIP 進行 ZIP 文件管理有哪些優勢?

IronZIP 簡化了 C# 中的 ZIP 文件管理,提供了簡便的方法來提取和創建 ZIP 存檔。它提高了軟件應用中的文件操作效率和組織性。

如何使用 C# 將多個文件壓縮到 ZIP 存檔中?

要在 C# 中將多個文件壓縮到 ZIP 存檔中,您可以使用 IronZIP 庫的 'IronArchive' 類別。它提供了將多個文件和目錄添加到單一壓縮存檔中的功能。

IronPDF 在 C# 中提供哪些 PDF 操作功能?

IronPDF 提供了包括 PDF 生成、轉換、操作和壓縮在內的多種功能,使開發人員能夠在 C# 應用中有效地處理 PDF 文件。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。