Search content within the blog

Thursday, July 29, 2010

Zip and Unzip files using IcsharpCode

Add a referece to the DLL Ichsarpcode.SharpZipLib in either your project where you want to use it else add it in GAC.

Code to compress/Zip
private static void CompressZip(string sPath)
{
ZipOutputStream zipOut = new ZipOutputStream(File.Create(@"C:\ZippedContents\test.zip"));
foreach (string fName in Directory.GetFiles(sPath))
{
FileStream sReader = File.OpenRead(fName);
byte[] buff = new byte[Convert.ToInt32(sReader.Length)];
sReader.Read(buff, 0, (int)sReader.Length);
FileInfo fi = new FileInfo(fName);
ZipEntry entry = new ZipEntry(fi.Name);
entry.DateTime = fi.LastWriteTime;
entry.Size = sReader.Length;
sReader.Close();
zipOut.PutNextEntry(entry);
zipOut.Write(buff, 0, buff.Length);
}
zipOut.Finish();
zipOut.Close();
Console.WriteLine("Done!!");
}

Where:sPath is the path to the folder you want to compress


Code to decompress/Unzip

private static void UncompressZip(string sFile)
{
ZipInputStream zipIn = new ZipInputStream(File.OpenRead(sFile));
ZipEntry entry;
while ((entry = zipIn.GetNextEntry()) != null)
{
FileStream streamWriter = File.Create(@"C:\UnzipHere\" + entry.Name);
long size = entry.Size;
byte[] data = new byte[size];
while (true)
{
size = zipIn.Read(data, 0, data.Length);
if (size > 0) streamWriter.Write(data, 0, (int)size);
else break;
}
streamWriter.Close();
}
Console.WriteLine("Done!!");
}
Where: sFile is the zip file you want to unzip.

1 comment:

  1. Once I had a problem with zip files. And luckily I found a good solution for solving like and other issues - zip fix, I was found it on an one soft blog.

    ReplyDelete