跳過到頁腳內容
使用 IRONZIP

C# ZIP 文件(使用 IronZip 的開發者教程)

ZIP is a popular method for efficiently compressing and consolidating multiple files and folders into a unified ZIP archive using FileStream. Working with these files in C# is made accessible using IronZIP namespace, which provides classes to create and extract existing ZIPs from a path or individual file contained and manipulate ZIP archives. Whether you're compressing files, dealing with password-protected ZIPs, or unzipping files, the ZipFile class within the IronZIP namespace becomes your invaluable ally.

In this tutorial, we not only explore the fundamental processes of creating and extracting ZIP archives but also learn code samples to achieve it. The ZipArchive class seamlessly progresses through the string path, enabling you to navigate and manipulate ZIP files with unparalleled precision.

Moreover, extending beyond ZIP manipulation, we'll also explore IronPDF, a tool for compressing PDF files without compromising document integrity. Together, the tandem of IronZIP and IronPDF equips developers with a robust set of tools to efficiently manage compressed files and streamline PDFs within the C# environment.

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 kick-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:

using IronZip;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply the IronZIP license key
            IronZip.Licensing.License.LicenseKey = "IRONZIP.MYLICENSE.KEY.1EF01";
            // Your ZIP manipulation code using IronZIP
        }
    }
}
using IronZip;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply the IronZIP license key
            IronZip.Licensing.License.LicenseKey = "IRONZIP.MYLICENSE.KEY.1EF01";
            // Your ZIP manipulation code using IronZIP
        }
    }
}
Imports IronZip

Namespace YourNamespace
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Apply the IronZIP license key
			IronZip.Licensing.License.LicenseKey = "IRONZIP.MYLICENSE.KEY.1EF01"
			' Your ZIP manipulation code using IronZIP
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

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

Create a ZIP File

Creating a ZIP file with IronZIP is simple. Utilize the IronArchive class to establish an empty ZIP archive and then add files to it. The following code snippet demonstrates the creation of a ZIP file named "Images.zip" and the addition of four image files to it:

using IronZip;

namespace CSharpZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an archive called Images.zip
            using (var archive = new IronArchive("Images.zip"))
            {
                // Add files to the ZIP
                archive.Add(@"E:\Datasets\1002-v1.png");
                archive.Add(@"E:\Datasets\1002-v2.png");
                archive.Add(@"E:\Datasets\1002-v3.png");
                archive.Add(@"E:\Datasets\1002-v4.png");
            }  // The archive is automatically closed here
        }
    }
}
using IronZip;

namespace CSharpZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an archive called Images.zip
            using (var archive = new IronArchive("Images.zip"))
            {
                // Add files to the ZIP
                archive.Add(@"E:\Datasets\1002-v1.png");
                archive.Add(@"E:\Datasets\1002-v2.png");
                archive.Add(@"E:\Datasets\1002-v3.png");
                archive.Add(@"E:\Datasets\1002-v4.png");
            }  // The archive is automatically closed here
        }
    }
}
Imports IronZip

Namespace CSharpZipArchive
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create an archive called Images.zip
			Using archive = New IronArchive("Images.zip")
				' Add files to the ZIP
				archive.Add("E:\Datasets\1002-v1.png")
				archive.Add("E:\Datasets\1002-v2.png")
				archive.Add("E:\Datasets\1002-v3.png")
				archive.Add("E:\Datasets\1002-v4.png")
			End Using ' The archive is automatically closed here
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

The using statement creates a scoped instance of the IronArchive class and associates it with the variable archive. The constructor of IronArchive takes a single argument: the name of a ZIP file ("Images.zip" in this case).

The code adds four files to the ZIP archive represented by the archive variable. The files are specified by their full paths:

  • E:\Datasets\1002-v1.png
  • E:\Datasets\1002-v2.png
  • E:\Datasets\1002-v3.png
  • E:\Datasets\1002-v4.png

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 "Images.zip" and adds four image files to it. IronZip made this super easy, fast, and efficient.

Extract ZIP File

We can extract a ZIP file using a single line of code in C#.

using IronZip; 

namespace YourNamespace
{
    public class ExtractionExample
    {
        public static void Main(string[] args)
        {
            // Extract contents of the ZIP archive
            IronArchive.ExtractArchiveToDirectory("Images.zip", "Extracted Images");
        }
    }
}
using IronZip; 

namespace YourNamespace
{
    public class ExtractionExample
    {
        public static void Main(string[] args)
        {
            // Extract contents of the ZIP archive
            IronArchive.ExtractArchiveToDirectory("Images.zip", "Extracted Images");
        }
    }
}
Imports IronZip

Namespace YourNamespace
	Public Class ExtractionExample
		Public Shared Sub Main(ByVal args() As String)
			' Extract contents of the ZIP archive
			IronArchive.ExtractArchiveToDirectory("Images.zip", "Extracted Images")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

The above code extracts the contents of the ZIP archive file named "Images.zip". The extracted files are placed in a directory named "Extracted Images". The IronArchive class provides the ExtractArchiveToDirectory method for this purpose, which makes extracting the content of a ZIP file very efficient.

csharp-zip-library-tutorial-1 This one-liner efficiently handles the extraction process, simplifying file management.

Add Files to an Existing ZIP file using C#

In C# software applications, adding files to an existing ZIP file is valuable for dynamic content management. Imagine a file manager application where users can easily expand a compressed archive by adding new files. IronZIP provides seamless functionality to modify any existing ZIP file.

using IronZip;

namespace CSharpZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Open an existing ZIP file and create a new one
            using (var archive = IronArchive.FromFile("Images.zip", "NewImages.zip"))
            {
                // Add new files to the ZIP
                archive.Add(@"E:\Datasets\1011-v1.png");
                archive.Add(@"E:\Datasets\1011-v2.png");
            }  // The new archive is automatically closed here
        }
    }
}
using IronZip;

namespace CSharpZipArchive
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Open an existing ZIP file and create a new one
            using (var archive = IronArchive.FromFile("Images.zip", "NewImages.zip"))
            {
                // Add new files to the ZIP
                archive.Add(@"E:\Datasets\1011-v1.png");
                archive.Add(@"E:\Datasets\1011-v2.png");
            }  // The new archive is automatically closed here
        }
    }
}
Imports IronZip

Namespace CSharpZipArchive
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Open an existing ZIP file and create a new one
			Using archive = IronArchive.FromFile("Images.zip", "NewImages.zip")
				' Add new files to the ZIP
				archive.Add("E:\Datasets\1011-v1.png")
				archive.Add("E:\Datasets\1011-v2.png")
			End Using ' The new archive is automatically closed here
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

The IronArchive.FromFile("Images.zip", "NewImages.zip") method creates an archive object from an existing ZIP file named "Images.zip" and specifies that the new archive should be named "NewImages.zip".

The two lines within the using block add files to the newly created archive:

  • archive.Add(@"E:\Datasets\1011-v1.png");
  • archive.Add(@"E:\Datasets\1011-v2.png");

These lines add the specified image files to the "NewImages.zip" archive.

File System

Compress PDF File

In addition to managing ZIPs, C# also offers the capability to compress PDF files seamlessly. This task is made achievable with the assistance of a third-party library: IronPDF. It stands out as a reliable solution for compressing PDFs while preserving their quality.

Introducing IronPDF

IronPDF is a versatile C# library designed to empower developers in efficiently handling PDF documents within their .NET applications. It provides many features, including PDF generation, manipulation, text and image extraction, forms handling, digital signatures, HTML to PDF conversion, PDF compression, and security enhancements. These capabilities make it an invaluable tool for tasks such as PDF creation, editing, report generation, and document management within the .NET framework, ensuring productivity and the ability to customize PDF operations.

Install IronPDF

To incorporate IronPDF into your project, execute the following command in the Package Manager Console:

Install-Package IronZip

Write a Code to Compress PDF File in C#

The following code sample demonstrates PDF file compression while maintaining the archive quality.

using IronPdf;

namespace YourNamespace
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Load the PDF document
            var pdf = new PdfDocument(@"E:\myPDF.pdf");

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

            // Save the compressed PDF
            pdf.SaveAs(@"E:\myCompressedPDF.pdf");
        }
    }
}
using IronPdf;

namespace YourNamespace
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Load the PDF document
            var pdf = new PdfDocument(@"E:\myPDF.pdf");

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

            // Save the compressed PDF
            pdf.SaveAs(@"E:\myCompressedPDF.pdf");
        }
    }
}
Imports IronPdf

Namespace YourNamespace
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Load the PDF document
			Dim pdf = New PdfDocument("E:\myPDF.pdf")

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

			' Save the compressed PDF
			pdf.SaveAs("E:\myCompressedPDF.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

In the above code, we open "myPDF.pdf" using IronPDF. The CompressImages method reduces image quality to 60%, and the compressed PDF is saved as "myCompressedPDF.pdf" in the specified location.

Output

Executing the above code yields a tangible reduction in file size, as evidenced by the output, where the compressed PDF's size is diminished to 254 KB from its original 0.9 MB size. This demonstrates the effectiveness of IronPDF in efficiently compressing PDF files without compromising their quality.

File Size Comparison

Efficient File Management with IronZIP and IronPDF in C#

In C# development, the combination of IronZIP and IronPDF presents a robust solution for comprehensive file management. IronZIP excels in efficiently compressing and manipulating ZIP files, offering developers a seamless experience for creating and extracting archives. Simultaneously, IronPDF serves as a powerful tool for handling PDF documents, enabling file compression while maintaining document integrity. This integration allows developers to navigate effortlessly between compressed archives and PDF files, enhancing the overall functionality and performance of their applications.

Whether compressing diverse files into a ZIP archive or optimizing PDF document sizes, the combined power of IronZIP and IronPDF forms a flexible toolkit for developers, addressing a range of file-related challenges.

Conclusion

In conclusion, IronZIP for C# offers robust capabilities for working with compressed files, enabling developers to create ZIP files, extract, and manipulate archives efficiently. IronPDF is also a powerful tool for compressing PDF files, making it easy to reduce file sizes while maintaining document integrity. Developers can leverage these features to enhance their applications' performance and functionality, ensuring the seamless handling of archived and compressed files. Furthermore, it's worth noting that IronPDF offers a flexible licensing model, including a free trial, allowing developers to explore its capabilities and determine the best fit for their projects. This trial period provides a valuable opportunity for developers to evaluate IronZIP's and IronPDF's features before committing to licensing.

常見問題解答

我怎樣才能在C#中創建ZIP檔案?

要在C#中創建ZIP檔案,可以使用IronZIP庫中的IronArchive類。此類允許創建空ZIP檔案並添加檔案,提供高效的ZIP內容管理方法。

如何在C#中從ZIP檔案提取檔案?

您可以使用IronZIP庫的IronArchive類中的ExtractArchiveToDirectory方法從ZIP檔案中提取檔案。此方法允許您指定將提取檔案的目錄。

我可以在C#中處理密碼保護的ZIP檔案嗎?

可以,IronZIP提供管理密碼保護ZIP檔案的功能,允許安全地壓縮和提取敏感數據。

在C#中安裝ZIP庫包的步驟是什麼?

要安裝IronZIP庫,請在NuGet包管理器控制台中使用命令Install-Package IronZip或直接從官方IronZIP NuGet網站下載。

如何在C#中應用ZIP庫的授權密鑰?

要為IronZIP應用授權密鑰,請將您的授權密鑰分配給應用程式中的Licensing.License類的LicenseKey屬性。

我怎樣才能在C#中壓縮PDF文件?

要在C#中壓縮PDF文件,可以使用IronPDF。加載PDF文件並應用CompressImages方法降低圖像質量,然後將壓縮的PDF保存到所需位置。

C#中的PDF庫是否有試用版本可用?

是的,IronPDF提供免費試用版本,允許開發者在簽署授權協定前探索其功能。

在C#中操作ZIP和PDF文件的前提條件是什麼?

要在C#中操作ZIP和PDF文件,您需要安裝Visual Studio或類似的C# IDE,並具備基本的C#編程概念。同時需要IronZIP和IronPDF庫。

處理ZIP文件的C#工具是什麼?

IronZIP是一個C#庫,旨在有效地創建、操作和提取ZIP檔案,非常適合在.NET應用中操作ZIP檔案的開發人員。

Curtis Chau
技術作家

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

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