Monday, February 25, 2008

Unzip File From C#

Unzipping a file from C# would always have been a tough job for me,if I had not found this utility in .Net.The java utility.To add this utility to our application,

Add reference to,

vjslib - version : v2.0.50727 in our project.

To make use of this utility add the following namespaces to application.

using java.util;
using java.util.zip;
using java.io;

This makes the unzipping features available in our application.

I shall include the code which I used to unzip a file below.

private List GetZipFiles(ZipFile zipfil)
{
List lstZip = new List();
Enumeration zipEnum = zipfil.entries();
while (zipEnum.hasMoreElements())
{
ZipEntry zip = (ZipEntry)zipEnum.nextElement();
lstZip.Add(zip);
}
return lstZip;
}

private void Extract(string zipFileName, string destinationPath)
{
ZipFile zipfile = new ZipFile(zipFileName);
List zipFiles = GetZipFiles(zipfile);
foreach (ZipEntry zipFile in zipFiles)
{
if (!zipFile.isDirectory())
{
InputStream s = zipfile.getInputStream(zipFile);
try
{
Directory.CreateDirectory(destinationPath + "\\backUp");
FileOutputStream dest = new
FileOutputStream(Path.Combine(destinationPath + "\\backUp\\",
Path.GetFileName(zipFile.getName())));
try
{
int len = 0;
sbyte[] buffer = new sbyte[7168];
while ((len = s.read(buffer)) >= 0)
{
dest.write(buffer, 0, len);
}
}
finally
{
dest.close();
}
}
finally
{
s.close();
}
Console.WriteLine("File Extraction Complete.");
}
}
}

Now to unzip the file just call,

Extract("[ZipFileName]","[UnzippedFilename]");

Hope this helps...

2 comments:

Cheeso42 said...

With VJ# being discontinued, and with the sheer size of the VJ# runtime being a problem sometimes, you may wanna look at alternatives for unzipping from C#.

http://www.codeplex.com/DotNetZip is one.

Alex said...

One day I unpacked my zip files and unexpectedly the light switched off. My data were lost. I decided to use the Inet. For luck I stumbled across there - how do i work on my corrupt zip files. The software solved my proposition quite hands down and I didn't waste the money.