Sunday, January 18, 2009

c# Code to Zip a folder with data and download them

Hey you can use this piece of c# method to zip data folder effectively.


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


public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
{
ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
// find number of chars to remove // from orginal file path
TrimLength += 1; //remove '\'
FileStream ostream;
byte[] obuffer;
string outPath = inputFolderPath + @"\" + outputPathAndFile;
ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
if (password != null && password != String.Empty)
oZipStream.Password = password;
oZipStream.SetLevel(9); // maximum compression
ZipEntry oZipEntry;
foreach (string Fil in ar) // for each file, generate a zipentry
{
oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
oZipStream.PutNextEntry(oZipEntry);

if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
{
ostream = File.OpenRead(Fil);
obuffer = new byte[ostream.Length];
ostream.Read(obuffer, 0, obuffer.Length);
oZipStream.Write(obuffer, 0, obuffer.Length);
}
}
oZipStream.Finish();
oZipStream.Close();
}//code for zipping files


Using the following code you can download zip files

private void Download(string _FilePath)//code for downloading files
{
Response.ContentType = "Application/Zip";
//string FilePath = MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
//Response.WriteFile(FilePath);
Response.AppendHeader("Content-Disposition", "Lecturer BackUp; filename=Backup.zip");
Response.TransmitFile(_FilePath);
Response.End();
}

No comments: