How to compress/decompress directories using GZipStream





5.00/5 (2 votes)
My alternative is to rather use a tried and tested compression api. It's simpler to use and you don't have to spend time developing helper methods to zip and unzip files.http://dotnetzip.codeplex.com/[^]Create a zip file using (ZipFile zip = new ZipFile()) { ...
My alternative is to rather use a tried and tested compression api. It's simpler to use and you don't have to spend time developing helper methods to zip and unzip files.
http://dotnetzip.codeplex.com/[^]
Create a zip file
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt");
zip.AddFile("7440-N49th.png");
zip.AddFile("2008_Annual_Report.pdf");
zip.Save("Archive.zip");
}
Extract a zip file
private void MyExtract()
{
string zipToUnpack = "C1P3SML.zip";
string unpackDirectory = "Extracted Files";
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
foreach (ZipEntry e in zip1)
{
e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
}
Create a downloadable zip within asp.net
public void btnGo_Click (Object sender, EventArgs e)
{
Response.Clear();
Response.BufferOutput= false; // for large files
String ReadmeText= "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G");
string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip";
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + filename);
using (ZipFile zip = new ZipFile())
{
zip.AddFile(ListOfFiles.SelectedItem.Text, "files");
zip.AddEntry("Readme.txt", "", ReadmeText);
zip.Save(Response.OutputStream);
}
Response.Close();
}
as well as various other uses.