How to Unzip a .zip file at runtime

If you are looking for the code to unzip a .zip file, then you are at the right place. The code is simple and easy. You can implement the code in your website in just 3 steps. So below are the steps.

Step 1) Create a file in App_Code folder named ZipUtil.cs and paste the below code in this ZipUtil.cs
using System;
using System.Data;
using System.Web;
using System.IO;
using System.Collections;
using ICSharpCode.SharpZipLib.Zip; //reference from ICSharpCode.SharpZipLib.dll
///
/// Summary description for ZipUtil
///
public static class ZipUtil
{
public static void UnZipFiles(string zipFile, string baseFolder)
{
if (!Directory.Exists(baseFolder))
{
Directory.CreateDirectory(baseFolder);
}
FileStream fr = File.OpenRead(zipFile);
ZipInputStream ins = new ZipInputStream(fr);
ZipEntry ze = ins.GetNextEntry();
while (ze != null)
{
if (ze.IsDirectory)
{
Directory.CreateDirectory(baseFolder + "\\" + ze.Name);
}
else if (ze.IsFile)
{
if (!Directory.Exists(baseFolder + Path.GetDirectoryName(ze.Name)))
{
Directory.CreateDirectory(baseFolder + Path.GetDirectoryName(ze.Name));
}
FileStream fs = File.Create(baseFolder + "\\" + ze.Name);
byte[] writeData = new byte[ze.Size];
int iteration = 0;
while (true)
{
int size = 2048;
size = ins.Read(writeData, (int)Math.Min(ze.Size, (iteration * 2048)), (int)Math.Min(ze.Size - (int)Math.Min(ze.Size, (iteration * 2048)), 2048));
if (size > 0)
{
fs.Write(writeData, (int)Math.Min(ze.Size, (iteration * 2048)), size);
}
else
{
break;
}
iteration++;
}
fs.Close();
}
ze = ins.GetNextEntry();
}
ins.Close();
fr.Close();
File.Delete(zipFile);// if you want to delete .zip file after conversion, otherwise don't write this line
}
}

Step 2) Add ICSharpCode.SharpZipLib.dll file in your application Bin folder.

Step 3) Use the following function in the page to unzip the .zip file

String Zipfilepath="C:\\YourFolder\\Yourzipfile.zip";
String DestinationFolder = "C:\\SomeOtherFolder\\";
ZipUtil.UnZipFiles(Zipfilepath, DestinationFolder);


and that’s it. Happy coding…

0 comments:

Post a Comment