.NET 3.0 provides some support for working with ZIP files. However, it has an important drawback: it only works for packages that are conformant to the Open Packaging Convention standard. Most of the ZIP files are not. Codeplex features a library called DotNetZip that provides support for packing and unpacking in C#, VB.NET or any other .NET language, but also any COM environment, including Javascript, VBSCript, VB6, VBA, PHP, Perl. In addition to the basic packing and unpacking operations, it supports password protection, UNICODE filenames, ZIP64 and AES encryption, comment, and others. Here are some simple samples.
Creating a ZIP file:
public static void PackZip(string source, string targetzip)
{
if(File.Exists(source))
{
PackFile(source, targetzip);
}
else if(Directory.Exists(source))
{
PackFolder(source, targetzip);
}
else
{
Console.WriteLine("Source does not exists!");
}
}
public static void PackFile(string file, string targetzip)
{
using (ZipFile zipfile = new ZipFile())
{
zipfile.AddFile(file, String.Empty);
zipfile.Save(targetzip);
}
}
public static void PackFolder(string folder, string targetzip)
{
using (ZipFile zipfile = new ZipFile())
{
zipfile.AddDirectory(folder);
zipfile.Save(targetzip);
}
}
Unpacking to a target folder:
public static void UnpackZip(string zippath, string targetdir)
{
if(ZipFile.IsZipFile(zippath))
{
using (ZipFile zipfile = ZipFile.Read(zippath))
{
foreach (ZipEntry zipentry in zipfile)
{
try
{
zipentry.Extract(targetdir, ExtractExistingFileAction.OverwriteSilently);
}
catch (ZipException ex)
{
if (ex.InnerException == null)
{
Console.WriteLine(ex.Message);
}
else
{
Console.WriteLine("{0}: {1}", ex.Message, ex.InnerException.Message);
}
}
}
}
}
else
{
Console.WriteLine("Not a zip file!");
}
}
Display the content of a ZIP archive:
public static void ShowZipContent(string zippath)
{
if(ZipFile.IsZipFile(zippath))
{
using(ZipFile zipfile = ZipFile.Read(zippath))
{
foreach(ZipEntry zipentry in zipfile)
{
Console.WriteLine("{0}", zipentry.FileName);
}
}
}
else
{
Console.WriteLine("Not a zip file!");
}
}
You can find many more examples on Codeplex: C# and VB.NET.










no comment untill now