Downloading files becomes a painful procedure if you have to select each individual file manually to perform the download. In this article we are going to select multiple files and download all of them as a single zip file.
Download SharpZipLib:
SharpZipLib is a free .NET API which is used to perform zipping operations. We will use SharpZipLib to perform the file zip.
Displaying the Files on the GridView Control:
We have created a folder in our application called "Files" which contains several text files. The first task is to display these files in the GridView control. The implementation is shown below:
The GridView ASPX code is shown below:
The first column contains CheckBoxes which will be used to select particular files to download. The second column displays the name of the file and also contains the file path as a hidden Label.
The output is shown below:
Next, we will add the ZipAllFiles custom method which will iterate through the selected files zip them as a single file and download it to the client's machine.
Zipping all Files and Downloading:
We have a folder called TempFiles in our server's folder where we will first create the temporary zip file. Later we will delete the zip file from the TempFolder. You can use any random name for the temporary file. We will be using GUID as the temporary file name. Let's see the complete implementation of the ZipAllFiles method.
The following line create a random unique file name:
Next, we iterate through the selected files and create a ZipEntry for each file. All ZipEnteries are placed in the ZipOutputStream by using the PutNextEntry method.
Finally, the ContentType for the response is set and header is adjusted to support the zip file format and the file is sent to the browser by using the Response.WriteFile method.
The screenshot below shows the client experiences a dialog box which allows them to open or save the zip file.
Conclusion:
In this article we demonstrated how to download multiple files as a single zip file.
[Download Sample]