Monday, June 30, 2008

Zip/UnZip using C# with help of iCSharpCode.Sharpziplib.dll

Code for Ziping Directories
///
/// Zip the complete directory with its complete subfolders
///

/// Complete path of the directory to zip
/// complete file path for the zipped file
public void ZipDirectory(string DirToZip, string OutputPath)
{
string[] filenames = Directory.GetFiles(DirToZip);
this.crc = new Crc32();
if(File.Exists(OutputPath))
File.Delete(OutputPath);
ZipOutputStream outStream = new ZipOutputStream(File.Create(OutputPath));
outStream.SetLevel(7); // 0 - store only to 9 - means best compression
zipdir(DirToZip);
outStream.Finish();
outStream.Close();
}

///
/// zip the direcotry and store the content to the zipdirecotry's zip file
///

/// Directory to zip
private void zipdir(string DirToZip)
{
string[] files = Directory.GetFiles(DirToZip);
foreach(string file in files)
zipfile(file);
string [] subdirs = Directory.GetDirectories(DirToZip);
foreach(string subdirectory in subdirs)
zipdir(subdirectory);
}


Code for UnZip Directories and its sub Directories

private void Unzip(string input ,string output)
{
ZipInputStream zipstream = new ZipInputStream(File.OpenRead(input));
ZipEntry theEntry;
while ((theEntry = zipstream.GetNextEntry()) != null)
{
string directoryName = output;
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName != "")
Directory.CreateDirectory(directoryName);
if (fileName != String.Empty)
{
if (theEntry.Name.IndexOf(".ini") < fullpath =" directoryName" fullpath =" fullPath.Replace(" fulldirpath =" Path.GetDirectoryName(fullPath);" streamwriter =" File.Create(fullPath);" size =" 2048;" data =" new" size =" zipstream.Read(data,"> 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
}
zipstream.Close();
}

Download :
iCSharpCode.sharpZipLib.dll