CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Creating/Generating ZIP files on the fly in C#/ASP.Net

By Satheesh Babu
Posted On Feb 12, 2011
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 1
Category: ASP.Net
Print this article.

Creating ZIP files on the fly in ASP.Net



Sometimes, we will get requirements where we need to zip the files at runtime before sending it to the client side. For example, if our application allows users to download multiple files at a time it will be better if we can zip it as a single file and make it available in a single download instead of downloading them individually. Doing this will give performance benefits and better user experience.

Moving forward, we will see how to create zip files on the fly using the free component dotnetzip in ASP.Net projects. According to the official page,

DotNetZip is an easy-to-use, FAST, FREE class library and toolset for manipulating zip files or folders. Zip and Unzip is easy: with DotNetZip, .NET applications written in VB, C# - any .NET language - can easily create, read, extract, or update zip files. For Mono or MS .NET.

Steps

1.      In your Visual Studio 2008, click File > New > WebSite. In the "New Web Site" dialog, Select "Asp.Net WebSite". In the Language DropDownlist at the bottom, choose C#. You can specify the name of the project in Location textbox.

2.      Download the latest dotnetzip component. The latest version as of this writing is v1.9.

3.      Unzip the DotNetZipLib-DevKit-v1.9.zip file. You can see unzipped folder contents as below.

Create zip file at runtime in asp.net

Navigate to DotNetZip-v1.9 folder where you will the .dll called Ionic.Zip.dll in Debug and Release folder. This is the assembly which is required to generate the zip files. Right click your project in the solution explorer and click “Add reference..”. Go to Browse tab and select the Ionic.Zip.dll in Release folder and click OK.

4.      For easy understanding purpose, we will copy some image files in the solution under the folder “Albums\Jokers”. We will use this content in our sample application to zip the content using dotnetzip component and send it to client. The solution will look like,

Compress or zip file dynamically in ASP.Net

Please remember, compressing any media files will not give you better results. I have just taken it as an example; you can use any text files or other files to see the difference. This article will just help you to use dotnetzip component for creating zip files on the fly in ASP.Net and will not deal with the actual compression techniques in detail.

5.      We will create a simple UI by displaying all the files found in the folder Albums\Jokers by displaying a checkbox near it. User can select the file and click the “Download as zip file” button to download it as a zip file. See the image below,

Creating ZIP files on the fly in ASP.Net Using Free Component dotnetzip

 

Below is the code used to build the above UI.

ASPX

<form id="form1" runat="server">

    <div>   

        <asp:CheckBoxList ID="chkAlbum" runat="server">

        </asp:CheckBoxList>

         <asp:Button ID="btnDownload" runat="server" onclick="btnDownload_Click"

            Text="Download as zip file" />

    </div>

 

CodeBehind

 protected void Page_Load(object sender, EventArgs e)

    {

        string[] files = Directory.GetFiles(Server.MapPath(".") + @"\Album\Jokers”);

       

        foreach (string file in files)

        {

            chkAlbum.Items.Add(new ListItem(Path.GetFileName(file), file));           

        }

    }

In the above code, i have used a CheckBoxList control to populate the files under Albums\Jokers folder. The text will show the file name and the value will hold the full path of the file.

In the coming sections, we will see how to zip the contents based on the user selection.

 

Creating Zip files at Runtime

To zip the selected files, we need to iterate over the Item collection of CheckBoxList control and check its “Selected” property. This will be true if the item is selected. We can include it in the zip file we create if the Selected is true. The dotnetzip component has a class called ZipFile which can be used to create the zip files. See the below code,

protected void btnDownload_Click(object sender, EventArgs e)

    {

        Response.Clear();      

        Response.ContentType = "application/zip";

        Response.AddHeader("content-disposition", "filename=" + "Album.zip");

 

        using (ZipFile zip = new ZipFile())

        {

            foreach (ListItem item in chkAlbum.Items)

            {

                if (item.Selected)

                {

                    zip.AddFile(item.Value,"Album");

                }               

            }          

            zip.Save(Response.OutputStream);

        }

    }

In the above code, we have used ZipFile.AddFile() method to add it to the zip file we are creating. The first parameter is the path of the file we are adding to zip and second is an optional parameter which will dictate the folder name under which the file will be archived in the zip file. If we didn’t supply the second parameter, the file will be created in the same hierarchy of the folders as it is found in the original file system in the zip file. That’s it! Execute the page and see it in action.

 

Zip entire folder

The code in the previous section helped to zip the files by adding them one by one. The dotnetzip component allows us to add a folder or directory instead of adding files individually using the ZipFile.AddDirectory() method. To this, drag another button and name it as btnDownLoadDir. See the below code,

protected void btnDownLoadDir_Click(object sender, EventArgs e)

    {

        Response.Clear();

        Response.ContentType = "application/zip";

        Response.AddHeader("content-disposition", "filename=" + "Album.zip");

        using (ZipFile zip = new ZipFile())

        {

            zip.AddDirectory(Server.MapPath(".") + @"\Album\Jokers");

            zip.Save(Response.OutputStream);

        }        

    }

 




Creating Password protected zip file

Sometimes, it is necessary to protect the zip files using password. The ZipFile class has a property called Password which can be used to set the password for the dynamically generated zip file using ZipFile class.  The below code will help us to do that,

protected void btnProtectedZIP_Click(object sender, EventArgs e)

    {

        Response.Clear();

        Response.ContentType = "application/zip";

        Response.AddHeader("content-disposition", "filename=" + "Album.zip");

 

        using (ZipFile zip = new ZipFile())

        {

            zip.Password = "test";

            foreach (ListItem item in chkAlbum.Items)

            {

                if (item.Selected)

                {

                    zip.AddFile(item.Value);

                }              

            }

            zip.Save(Response.OutputStream);

        }

    }

The downloaded zip can be opened only if we provide the password “test”.

 

Creating Zip file from Stream at runtime

Sometimes, there will be requirements where we need to create a zip file from the stream (byte[]) and send it to client. For example, you may need to create a zip file from the file uploaded using the FileUpload control.  You can use FileUpload1.FileContent property to get the stream of bytes that is uploaded using FileUpload control. Similarly, the below example will read a text file as a stream and will create a zip file out of it. Refer the below code,

protected void btnDownloadstream_Click(object sender, EventArgs e)

    {

        Response.Clear();

        Response.ContentType = "application/zip";

        Response.AddHeader("content-disposition", "filename=" + "file.zip");

 

        using (ZipFile zip = new ZipFile())

        {

            zip.AddEntry("textfile.txt", File.ReadAllBytes(Server.MapPath(".")+@"\App_data\DataFile.txt"));         

            zip.Save(Response.OutputStream);

        }

    }

 

Creating Zip file and Saving it in File System

This is one of the most frequent requirements we will get when dealing with creating zip file. The ZipFile class has a method called Save() which can be used to save the generated zip file to a file system. See the below code,

protected void btnSaveasZIP_Click(object sender, EventArgs e)

    {

        string destdir = Server.MapPath(".") + @"\ZIPs\"+"Album.zip";   

 

        using (ZipFile zip = new ZipFile())

        {

            foreach (ListItem item in chkAlbum.Items)

            {

                if (item.Selected)

                {

                    zip.AddFile(item.Value);

                }              

            }

            zip.Save(destdir);

        }

        Response.Write("Zip file is generated and saved in "+destdir);

    }

 

Downloads

Download source

 

Conclusion

Thus, creating zip file dynamically will help us in big time when our application deals with lot of files. This includes improving application performance, saving bandwidth, space etc. Download the source attached with this article to see it in action.

To know more, you can refer the DotNetZipLib-v1.9.chm help file which has all the information on how to use this component.

Happy coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Zip File
Hi!

This is a nice article. Thanks for sharing your knowledge because some time need to download files in a single zip folder

because this is a better way to download multiple files. I have find out some other links that's also helpful for

developers.

http://www.campusmvp.net/blog/asp-net-mvc-return-of-zip-files-created-on-the-fly

http://www.mindstick.com/Blog/439/File%20download%20in%20zip%20Folder%20in%20ASP%20NET%20MVC%204