System.IO.Compression Namespace in C# .Net provides GZipStream and DeflateStream classes to compress and de-compress gzip files and Deflated files respectively.
But our scope is to de-compress or UNZIP files using .Net C#. C# in native does not provides classes to compress (zip) or de-compress (unzip) .zip files.
#ziplib (SharpZipLib, formerly NZipLib) open source library helps us to zip and un-zip .zip files, which is written entirely in C# for the .NET platform. It is free, C# source code included!
The required of .net version"ICSharpCode.SharpZipLib.dll" file can be downloaded from http://www.icsharpcode.net/OpenSource/SharpZipLib/ and can referenced to the required project.
The sample code for unzip .zip files in .Net C# using #ziplib (SharpZipLib) is below
Namespace used:using System.IO; using ICSharpCode.SharpZipLib.Zip;
public static bool UnZipFile(string InputPathOfZipFile)
{
bool ret = true;
try
{
if (File.Exists(InputPathOfZipFile))
{
string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile);
using (ZipInputStream ZipStream = new
ZipInputStream(File.OpenRead(InputPathOfZipFile)))
{
ZipEntry theEntry;
while ((theEntry = ZipStream.GetNextEntry()) != null)
{
if (theEntry.IsFile)
{
if (theEntry.Name != "")
{
string strNewFile = @"" + baseDirectory + @"\" +
theEntry.Name;
if (File.Exists(strNewFile))
{
continue;
}
using (FileStream streamWriter = File.Create(strNewFile))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = ZipStream.Read(data, 0, data.Length);
if (size > 0)
streamWriter.Write(data, 0, size);
else
break;
}
streamWriter.Close();
}
}
}
else if (theEntry.IsDirectory)
{
string strNewDirectory = @"" + baseDirectory + @"\" +
theEntry.Name;
if (!Directory.Exists(strNewDirectory))
{
Directory.CreateDirectory(strNewDirectory);
}
}
}
ZipStream.Close();
}
}
}
catch (Exception ex)
{
ret = false;
}
return ret;
}
The "UnZipFile" function can be used as
UnZipFile(@"C:\games.zip");
The above "UnZipFile" function can be used to unzip .zip files. "UnZipFile" function is self explanatory. Required file to be extracted is given to "ZipInputStream" class, which provides all entries (files/folder) found in .zip file. Each entry is checked, new folders are created for directory entry and files are created using "FileStream" for file entries. Thus required .zip files are extracted.
The files and folder unzipped are extracted to same folder as that of input file.
#ziplib also compresses and de-compresses GZip, Tar and BZip2 formats.
Thanks for the #ziplib developers and its maintainer, who has given a great piece of library.
check this link to unzip .gzip files using .net c#
Thanks, best explanation ever
hi, than for your code ..but it's not work for non-English files name :( plz help
Very nice Solution That Help ME Alot Thank u