SoFunction
Updated on 2025-03-08

C# Use SharpZipLib to compress and decompress files

1. Introduction

SharpZipLib is a ZIP, GZIP, Tar and BZIP2 Library written entirely in C#, which can conveniently support compression and decompression in these formats.

/icsharpcode/SharpZipLibDownload and unzip SharpZipLib and add .dll to the project reference.

2. Operation Guide

1.1 Create a zip file and add the file:

using (ZipFile zip = (@"E:\"))
{
    ();
    (@"E:\file");
    (@"E:\file");
    ();
}

1.2 Compress folders into files

(new FastZip()).CreateZip(@"E:\", @"E:\test\", true, "");

The last parameter is the filter file rules represented by regular expressions. The CreateZip method has 3 overloaded versions, including directory filtering parameters, file filtering parameters and a bool-type parameter that specifies whether to perform subdirectory recursion.

1.3 Add files to existing zip files

using (ZipFile zip = new ZipFile(@"E:\"))
{
    ();
    (@"E:\");
    ();
}

1.4 List files in zip file

using (ZipFile zip = new ZipFile(@"E:\"))
{
    string list = ;
    foreach (ZipEntry entry in zip)
    {
        list +=  + "\r\n";
    }
    (list);
}

1.5 Delete a file in the zip file

using (ZipFile zip = new ZipFile(@"E:\"))
{
    ();
    (@"");
    (@"");
    ();
}

1.6 Unzip the file in the zip file and into the specified directory

(new FastZip()).ExtractZip(@"E:\", @"E:\test\", "");

3. Commonly used categories

ZipInputStream and GZipInputStream are used to decompress Deflate and GZip format streams.

ZipOutputStream and GZipOutputStream are used to compress Deflate and GZip format streams.

The StreamUtil class contains several Stream processing helper methods:

1) Copy(Stream, Stream, Byte[]) is used to copy data from one Stream object to another Stream object. There are multiple rewrites.

2) ReadFully(Stream, Byte []) is used to read all byte data from Stream objects. There are multiple rewrites.

This is all about this article about using SharpZipLib to compress and decompress files in C#. I hope it will be helpful to everyone's learning and I hope everyone will support me more.