Compress and Download Zip
public static void CompressAndDownload(HttpResponseBase _response, string zipFilename, List<FileCompressInfo> files)
{
MemoryStream outputMemStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
byte[] bytes = null;
foreach (var file in files)
{
var newEntry = new ZipEntry(file.Filename);
newEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newEntry);
bytes = file.Bytes;
MemoryStream inStream = new MemoryStream(bytes);
StreamUtils.Copy(inStream, zipStream, new byte[4096]);
inStream.Close();
zipStream.CloseEntry();
}
zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream.
outputMemStream.Position = 0;
MemoryStream ms = new MemoryStream(outputMemStream.ToArray());
var downloadFilename = string.Format("{0}_{1}", System.DateTime.Now.ToString("yyyy-MM-dd"), zipFilename);
_response.Clear();
_response.AddHeader("content-disposition", "attachment; filename=" + downloadFilename);
_response.ContentType = "application/octet-stream";
_response.Buffer = true;
ms.WriteTo(_response.OutputStream);
_response.End();
}
}
public class FileCompressInfo
{
public string Filename { get; set; }
public byte[] Bytes { get; set; }
}