COMPARE TO OTHER COMPONENTS

Zip Archive Tutorial for C# Developers Using IronXL

Published October 30, 2023
Share:

ZIP archives are a popular format for compressing and packaging a single file or entire collection of multiple files into a single ZIP package container or ZIP file. In C#, you can easily work with ZIP archives using the System.IO.Compression namespace, which provides classes like ZipArchive and ZipFile to perform various operations on ZIP files. In this tutorial, we'll explore how to create ZIP files, extract data from compressed files, and manipulate ZIP archives in C# using relative path.

Prerequisites

  1. A basic understanding of C# programming.
  2. Visual Studio or any C# development environment.

Step 1: Create a New C# Project

Open your C# development environment and create a new C# project to implement Zip archive and compressed text file functionality using ZipArchive archive=new ZipArchive(). You can choose either a Console Application or any other suitable project type for your use case.

Step 2: Create a Zip Archive from a folder in C

We can easily create a new Zip archive from an existing directory using ZipFile.CreateFromDirectory() method as shown in the following example.

static void Main(string [] args)
{
ZipFile.CreateFromDirectory(@"D:\Certificate", @"D:\Certificate.zip", CompressionLevel.SmallestSize, true);
}
static void Main(string [] args)
{
ZipFile.CreateFromDirectory(@"D:\Certificate", @"D:\Certificate.zip", CompressionLevel.SmallestSize, true);
}
Shared Sub Main(ByVal args() As String)
ZipFile.CreateFromDirectory("D:\Certificate", "D:\Certificate.zip", CompressionLevel.SmallestSize, True)
End Sub
VB   C#

The first parameter @"D:\Certificate" specifies the source directory to be compressed, while the second parameter @"D:\Certificate.zip" designates the location and name of the resulting ZIP archive. The third parameter CompressionLevel.SmallestSize determines the compression level, with SmallestSize indicating the smallest file size even if it takes longer to compress binary data. The fourth parameter, true, specifies whether to preserve the directory structure and file system within the ZIP archive, ensuring that the folder's structure is maintained.

Step 3: Update a Zip Archive in C#

In the following example, we will illustrate the process of working with an existing ZIP archive in C#. Specifically, we will explore how to open an already created ZIP package using ZipArchive archive=zipfile.openread, modify its contents, and append a new file and an existing file.

 using (FileStream zipToOpen = new FileStream(@"D:\Invoices.zip", FileMode.Open))
 {
//var archive= new ZipArchive
     using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
     {
         archive.CreateEntryFromFile(@"D:/Invoice.pdf", "Invoices/myInvoice.pdf");
         ZipArchiveEntry entry = archive.CreateEntry("Readme.txt");
//using StreamWriter writer=new StreamWriter
         using (StreamWriter writer = new StreamWriter(entry.Open()))
         {
            writer.WriteLine("This folder contains the file compressed using C#");
            writer.WriteLine("========================");
         }
     }
 }
 using (FileStream zipToOpen = new FileStream(@"D:\Invoices.zip", FileMode.Open))
 {
//var archive= new ZipArchive
     using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
     {
         archive.CreateEntryFromFile(@"D:/Invoice.pdf", "Invoices/myInvoice.pdf");
         ZipArchiveEntry entry = archive.CreateEntry("Readme.txt");
//using StreamWriter writer=new StreamWriter
         using (StreamWriter writer = new StreamWriter(entry.Open()))
         {
            writer.WriteLine("This folder contains the file compressed using C#");
            writer.WriteLine("========================");
         }
     }
 }
Using zipToOpen As New FileStream("D:\Invoices.zip", FileMode.Open)
'var archive= new ZipArchive
	 Using archive As New ZipArchive(zipToOpen, ZipArchiveMode.Update)
		 archive.CreateEntryFromFile("D:/Invoice.pdf", "Invoices/myInvoice.pdf")
		 Dim entry As ZipArchiveEntry = archive.CreateEntry("Readme.txt")
'using StreamWriter writer=new StreamWriter
		 Using writer As New StreamWriter(entry.Open())
			writer.WriteLine("This folder contains the file compressed using C#")
			writer.WriteLine("========================")
		 End Using
	 End Using
End Using
VB   C#

The above code opens an existing ZIP archive at "D:\Invoices.zip" in read mode, using a FileStream, and creates a ZipArchive in update mode for both reading and modifying the archive's content. It then employs the CreateEntryFromFile method to add "Invoice.pdf" from "D:" to the archive, placing it within the "Invoices" directory and naming it "myInvoice.pdf."

Invoices Directory

Step #4: Extract a Zip Archive

The following C# code extracts the contents of a ZIP file into a specified directory.

ZipFile.ExtractToDirectory(@"D:\Certificate.zip", @"D:\ExtractedCertificate");
ZipFile.ExtractToDirectory(@"D:\Certificate.zip", @"D:\ExtractedCertificate");
ZipFile.ExtractToDirectory("D:\Certificate.zip", "D:\ExtractedCertificate")
VB   C#

The above lines of code decompress files from the ZIP archive. It specifies the source ZIP archive located at "D:\Certificate.zip" and designates the destination directory as "D:\ExtractedCertificate." The code unzips the archive, placing its contents into the specified directory. You can provide the absolute path or relative path of the directory you are working in to create a compressed text file.

Introducing IronPDF

IronPDF is a versatile and powerful C# library that simplifies the creation, manipulation, and rendering of PDF documents in .NET applications. It provides developers with the classes and methods to easily generate, edit, and convert PDF files within their C# projects. Whether you need to create PDF reports, invoices, or interactive forms, IronPDF offers a wide range of features and capabilities, making it an indispensable library for businesses and developers who require comprehensive PDF functionality in their .NET applications. With IronPDF, you can seamlessly integrate PDF generation and manipulation into your C# applications, enabling the efficient handling of various PDF-related tasks.

Features of IronPDF

IronPDF offers a comprehensive set of features and capabilities for working with PDFs in C# applications. Some of its key features include:

PDF Generation: You can easily create new PDF documents or modify existing ones using a wide range of text, images, and graphical elements.

HTML to PDF Conversion: Convert HTML pages, URLs, or even raw HTML content to PDF with high-fidelity rendering. This is particularly useful for generating reports or capturing web content.

PDF Rendering: Render PDFs for display in applications, allowing you to view and interact with PDF documents directly within your C# program.

PDF Editing: Modify existing PDF documents by adding, deleting, or updating text, images, and other content. You can also manipulate page layout and structure.

PDF Forms: Create, fill, and extract data from interactive PDF forms, making it easy to work with surveys, questionnaires, and other data capture applications.

PDF Encryption: Protect PDFs by encrypting them with various encryption algorithms and setting permissions for viewing, editing, and printing.

PDF Text Extraction: Extract text and data from PDF documents, making it simple to parse and analyze content for indexing, search, or data extraction.

Image and Graphics Support: Add and manipulate images, shapes, and graphical elements in PDFs, allowing for rich visual content.

PDF Printing: Print PDFs directly from your C# application to physical or virtual printers.

Advanced Text Formatting: Apply various font styles, colors, and formatting options to text in your PDF documents.

PDF Merging and Splitting: Combine multiple PDF documents into one or split a large PDF into smaller sections as needed.

PDF Accessibility: Ensure your PDF documents are accessible to individuals with disabilities by adding accessibility features like tags and alternative text.

Cross-Platform Support: IronPDF works on both Windows, Mac, and Linux environments, enabling you to build cross-platform applications.

Licensing Options: IronPDF offers flexible licensing options, including free trial versions, for developers to choose the best fit for their needs.

Conclusion

In conclusion, working with ZIP archives in C# offers a valuable set of tools for various scenarios, from compressing files for storage or distribution to managing data efficiently. Whether you're creating, extracting, or manipulating ZIP archives, the System.IO.Compression namespace provides a user-friendly and powerful toolkit. Additionally, while ZIP archives are essential for managing file-related tasks, it's worth noting that in more extensive document and report generation scenarios, libraries like IronPDF extend the capabilities of C# applications, offering comprehensive PDF generation, editing, and rendering, making it a robust choice for more complex document-centric requirements. By combining the native ZIP archive capabilities of C# with the advanced PDF functionalities of IronPDF, developers can create versatile and complete document management solutions to meet their diverse needs.

< PREVIOUS
A Comparison between IronXL and GemBox.Spreadsheet
NEXT >
EPPlus Read Excel to Datatable C# (IronXL Tutorial)

Ready to get started? Version: 2024.11 just released

Free NuGet Download Total downloads: 1,111,773 View Licenses >