DEV Community

Miguel Teheran
Miguel Teheran

Posted on

4 1 1 1 1

How to read zip files with SharpZip library in C#

SharpZip library is a great library to work with compressed files like .zip. This library supports Zip, GZip, BZip2, and Tar.

To use this library, add it to your project using the package manager in Visual Studio or with the following command.

dotnet add package SharpZipLib --version 1.4.2
Enter fullscreen mode Exit fullscreen mode

First, we need to add the following namespace to the project.

using ICSharpCode.SharpZipLib.Zip;
Enter fullscreen mode Exit fullscreen mode

Then to read the file, we need to define the path; it could be a relative or absolute route.

var myZipPath = "test.zip";
Enter fullscreen mode Exit fullscreen mode

With this simple code snippet, we can loop through all the files in the zip and read their content.

using (ZipFile zipFile = new ZipFile(myZipPath))
{
    foreach(ZipEntry zip in zipFile)
    {
        Console.WriteLine(zip.Name);
        using (StreamReader reader = new StreamReader(zipFile.GetInputStream(zip)))
        {
            Console.WriteLine($"Content: {reader.ReadToEnd()}");
            reader.Close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

You can also check if the ZipEntry value is a folder or a file to avoid issues reading the information. We have a simple condition. We can validate it.

using (ZipFile zipFile = new ZipFile(myZipPath))
{
    foreach(ZipEntry zip in zipFile)
    {
        if(!zip.IsDirectory)
        {
            Console.WriteLine(zip.Name);
            using (StreamReader reader = new StreamReader(zipFile.GetInputStream(zip)))
            {
                Console.WriteLine($"Content: {reader.ReadToEnd()}");
                reader.Close();
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Miguel Teheran,
Excellent content, very useful.
Thanks for sharing.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay