Thursday, January 6, 2011

Unzip Files and Folders C#

Easy Method to extract data from zip file is usng Shell Object.

Add reference to Shell32 ("C:\Windows\System32\Shell32.dll")
********************

Shell objShell = new Shell();
Folder shellZipFile = objShell.NameSpace("\\zipfileName and Path')
Folder shellUnZipFile = objShell.NameSpace("UnzipFolderName and path")
foreach (FolderItem zipFileitem in shellZipFile.Items())
{
shellUnZipFile.CopyHere(zipFileitem, 0);
}

This code may create a "file exist" error .. in some strange PC's :)

if u get such error i donno wat s the root cause but i have another solution


download
ICSharpCode.SharpZipLib.Zip;

add the
ICSharpCode.SharpZipLib.Zip reference

use the below code
*****************************

public void UnZipUtil()
{
try
{
string[] temp;
if (Directory.Exists("\\UnzipFolderPathand Name")
{
Directory.Delete("\\UnzipFolderPathand Name", true);
Directory.CreateDirectory("UnzipFolderPathand Name");
}
else
{
Directory.CreateDirectory("UnzipFolderPathand Name");
}
using (ZipInputStream zipFileStream = new ZipInputStream(File.OpenRead("zipFilePath\\zipFileName)))
{
ZipEntry theEntry;
string tmpEntry = String.Empty;
while ((theEntry = zipFileStream.GetNextEntry()) != null)
{
string directoryName = "Unzipfolderpath\\name";
string fileName = Path.GetFileName(theEntry.Name);
// create directory
if (directoryName != "")
{
Directory.CreateDirectory(directoryName);
}
if (fileName != String.Empty)
{
if (theEntry.Name.IndexOf(".ini") < 0)
{
string fullPath = directoryName + "\\" + theEntry.Name;
fullPath = fullPath.Replace("\\ ", "\\");
string fullDirPath = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
FileStream streamWriter = File.Create(fullPath);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = zipFileStream.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
}
}
}