Reading Zip Files with SharpZip Library in .NET

Introduction

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

Reading Zip Files with SharpZip Library

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

dotnet add package SharpZipLib --version 1.4.2

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

using ICSharpCode.SharpZipLib.Zip;

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

var myZipPath = "test.zip";

And finally, with the following simple snippet, we can loop between all the files included in the zip and read the 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();
        }
    }
}

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();
            }
        }
    }
}


Similar Articles