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
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";
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();
}
}
}
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();
}
}
}
}
Top comments (1)
Hi Miguel Teheran,
Excellent content, very useful.
Thanks for sharing.