DEV Community

Miguel Teheran
Miguel Teheran

Posted on

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

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

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