Zip files and folders in .NET

A lot of solutions exists that show how to zip files in .NET, for example some of them using SharpZipLib, GZipStream, Windows Shell API or the ZipLibrary class. However one lesser known solution which I have found to be very useful is the DotNetZip library

As given on the site - “DotNetZip is an easy-to-use FREE class library and toolset for manipulating zip files or folders. Zip and Unzip is easy: with DotNetZip, .NET applications written in VB, C# - any .NET language - can easily create, read, extract, or update zip files. It works on Mono or MS .NET”

You can download DotNetZip Library over here.

Here’s a sample that shows how to use this library to zip all files in a folder

C#

using System;
using Ionic.Zip;

namespace ZipSample
{
class Program
{
static void Main(string[] args)
{
try
{
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(@"D:\Ajax");
zip.Save(@"D:\Ajax\Ajax.zip");
Console.WriteLine("Files zipped");
}
}
catch (ZipException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

VB.NET

Imports System
Imports Ionic.Zip

Namespace ZipSample
Class Program
Shared Sub Main(ByVal args() As String)
Try
Using
zip As New ZipFile()
zip.AddDirectory("D:\Ajax")
zip.Save("D:\Ajax\Ajax.zip")
Console.WriteLine("Files zipped")
End Using
Catch
ex As ZipException
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
End Class
End Namespace
Depending on the size of the files in a folder, it may take some time for the zip operation to complete.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Unknown said...

Very Useful.. Thank you so much for reducing my effort :)