Extracting the content of a ZIP file is really common. And here is a simple example of how to do it with C# using ZipFile and SharpZipLib.
If you are using .Net Framework 4.6.0 or up you can use System.IO.Compression.ZipFile from Microsoft. But if you are lower than 4.6 then you can use SharpZipLib from ICSharpCode (both are available on NuGet).
ZipFile
using System;
using System.IO.Compression;
class Program
{
static void Main(string[] args)
{
string zipFile = @"C:\temp\myzipfile.zip";
string extractionPath = @"C:\temp\unzipped";
ZipFile.ExtractToDirectory(zipFile, extractionPath);
}
}
Code language: C# (cs)
SharpZipLib
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
namespace Unzip_Demo
{
class Program
{
static void Main(string[] args)
{
string zipFilePath = @"C:\temp\test.zip";
string extractionPath = @"C:\temp\extract";
UnZip(zipFilePath, extractionPath);
}
public static void UnZip(string srcFile, string dstFolder)
{
ZipFile zf = null;
try
{
FileStream fs = File.OpenRead(srcFile);
zf = new ZipFile(fs);
foreach (ZipEntry zipEntry in zf)
{
if (!zipEntry.IsFile) continue; //Ignore directories
var entryFileName = zipEntry.Name;
var buffer = new byte[4096]; //4K is optimum
var zipStream = zf.GetInputStream(zipEntry);
var fullZipToPath = Path.Combine(dstFolder, entryFileName);
var directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName != null && directoryName.Length <= 0) continue;
if (directoryName != null) Directory.CreateDirectory(directoryName);
using (var streamWriter = File.Create(fullZipToPath))
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
catch (Exception)
{
throw;
}
finally
{
if (zf != null)
{
zf.IsStreamOwner = true;
zf.Close();
}
}
}
}
}
Code language: C# (cs)
Happy coding! 🙂