Introduction
his tip demonstrates how to create directory within the zip file and then add entries like HTML, XML, .txt files in it. For this purpose, I am using Ionic.Zip.ZipFile
which is a third party DLL. You can download it from dotnetzip.codeplex.com. In the downloaded file, you can make use of the documentation as well.
Background
While I was working for my project, I came across a situation where I was generating HTML, text and XML files. I want to make a zip file so that user can download it accordingly. Everything works fine but then I want to enhance this by creating different folders, i.e., directories based on my report categories. This is something I encountered while I was making some files to be zipped and then downloading them.
Using the Code
I was dynamically creating HTML and then I was creating a zip file like:
using(ZipFile file = new ZipFile())
{
file.AddEntry(''myHtml''+'''.html',''generatedHtml'');
file.AddEntry(''myXml''+'''.xml',''generatedXml'');
file.AddEntry(''myText''+'''.txt',''generatedTxt'');
Response.ClearContent();Response.ClearHeaders();
Response.AppendHeader("content-disposition","attachment;filename=Report.zip");
file.Save(Response.OutputStream);
}
and then saving the zip file on output stream. It's working fine, ZipFile download option pops up in the browser and is downloaded wherever user saves it like:
Report.zip-> myHtml,myXml,myText
These three files are extracted in the root of the zip File. But, what I need to do was that I want to add a folder in the root and add these files to it, based on categories I have to make different folders into it and then zip it. The thing to notice is that I don't know path of folder where I can zip my three files because it will be user who will save it wherever he/she may want.
Report.zip->myCategory1->myHtml,myXml,myText
Report.zip->myCategory2->myHtml,myXml,myText
The solution to this is actually quite simple and easy which is to include the folder name. Just remember the add entry is based on key value so two files with same name cannot resist.
file.AddEntry("myFolder1/myhtml1.html", "<div>This is Saad</div>");
It doesn't matter if you use a forward slash (/) or a backslash (\) for the path separator, as the code will fix up the path as necessary. However, to use a backslash from C#, you'd either need to escape it, or use a verbatim string
.
file.AddEntry("myFolder1\\myhtml1.html", "<div>This is Some Html</div>");
file.AddEntry(@"myFolder1\myhtml1.html", "<div>This is Some Html</div>");