How to zip a file or a folder in ASP.NET

You can zip a file or a folder in ASP.NET by using, ICSharpCode.SharpZipLib.Zip or other library assemblies.

C# in Depth, 3rd EditionManaged Windows VPS Hosting

SharpZipLib can be downloaded from:

The ASP.NET examples below demonstrate how to zip files.

using ICSharpCode.SharpZipLib.Zip;
using System.IO;

ZipOutputStream zos = null;
protected void Button1_Click(object sender, EventArgs e)
string[] pathCollection = new string[2];
PathCellction[0] = “c:\\folder1”;
PathCellction[1] = “c:\\folder2”;
StartZip(pathCollection, “filename”);

protected void StartZip(string[] pathCollection, string strFileName)
MemoryStream ms;
Response.ContentType = “application/octet-stream”;
strFileName = HttpUtility.UrlEncode(strFileName).Replace(‘+’, ‘ ‘);
Response.AddHeader(“Content-Disposition”, “attachment; filename=” + strFileName + “.zip”);
ms = new MemoryStream();
zos = new ZipOutputStream(ms);

protected void addZipEntry(string[] pathCollection)
for (int i = 0; i < pathCollection.Length; i++) { string strPath = pathCollection[i]; addZipEntry(strPath, strPath.LastIndexOf("\\") + 1); } }protected void addZipEntry(string strPath, int baseIndex) { DirectoryInfo di = new DirectoryInfo(strPath); foreach (DirectoryInfo item in di.GetDirectories()) { addZipEntry(item.FullName, baseIndex); } foreach (FileInfo item in di.GetFiles()) { FileStream fs = File.OpenRead(item.FullName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string strEntryName = item.FullName.Remove(0, baseIndex); ZipEntry entry = new ZipEntry(strEntryName); zos.PutNextEntry(entry); zos.Write(buffer, 0, buffer.Length); fs.Close(); } }