Download Files from Grid-view in Zip Format using Dot Net Zip

Raj.Trivedi
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 9350 red flag
Rating: 4 out of 5  
 1 vote(s)

In this article we will see how we can download files from grid view in zip format.We will be using a 3rd Party Tool named Iconic-zip to achieve the task.

Introduction


Sometimes we are given task to download the files from a server that are uploaded.These task can be useful for administrators and Users using the Web.Just sometime back on of my friend asked me can we download multiple files in ZIP archieve. After researching a lot there was one utility that can help us to achieve the task.

Objective


  1. Obtaining Ionic Zip Utility
  2. Embedding the Ionic Zip Utility
  3. Binding the Files to Grid View with Path(Bind Grid-ViewFunction)
  4. Downloading files in a ZIP archive

Obtaining the Iconic Zip Utility :-
  1. Ionic Zip Utility is open source project announced on sourceforge.net under dotnetzip umbrella.This utility allows us to create zip archives.
  2. Obtain the Ionic Zip Utility from : http://dotnetzip.codeplex.com/downloads/get/258014?releaseId=68268&ProjectName=dotnetzip
Embedding the Ionic Zip Dll in asp.net

  1. Create a New Empty Website in VS 2010.
  2. Once we have downloaded the file.We need to extract them in a folder.
  3. Once we extract them we need to add them to our asp.net application
  4. First we need to add a Bin folder in asp.net application
  5. To Add a Bin Folder -> Right Click on Website -> Add ASP.NET Folder -> Bin.
  6. Now its time to add the IconicZip dll.Now right click on Bin Folder and add Click Existing item and browse to the folder where we have extracted the files.
  7. We need to zip-v1.9-Reduced folder and then go to Ionic.Zip.Reduced dll and select and add it.(Please Check Screens. 1,2 and 3) 

Screen 1




Screen 2




Screen 3 : Bin Folder





Using the code

  1. Import the following namespaces using System.IO and using Ionic.Zip
  2. Now add a File Upload control, 1 button , 1 Grid View, 1 Button to Download.
  3. Now go to Grid View and Add and Item Template field and add a check box to select the files.(Check Screen 4 for User Interface)
  4. Lets start Implementation.
  5. Now on upload button click event we will upload the file using the server.mappath method(Check Code for review)
  6. Server.Mappath allows us to upload the file to a Specific folder with the file name.
  7. Now we will create a Function to bind a Grid View(Check Explanation Below).
  8. Now we right the logic for downloading the files for using the Iconic.Zip.Logic Explained Below the Explanation of Grid-view Binding
Explanation of Grid-view Binding

  1. We create an string array to get the files from the folder.
  2. Now we create an object of List which has type of ListItems
  3. We then run a foreach loop to get path of each files and store in a Variable type of string named files and then assign the datasource as files(string variable which is storing the path) and then bind it to grid view.

Downloading the Files as a Zip Archieve

  1. First we create an Instance ZipFile class provided by Ionic.Zip
  2. Then we run a foreach loop on the rows and find the checkbox control and check which of the checkbox has been checked.
  3. Once we get the files that are checked we get the name of the files and their and finally add them by using the AddFile method provided by the Iconic.zip
  4. Then we assign the name to the archive that we have created by adding the file.
  5. We then set the Type to "application/zip" to assign the extension
  6. Finally we save the Zip File using the Save method given by the Ionic.Zip Class pass the Outstream as a Parameter.
  7. This will then download the file(Output on Screen 5)




Screen 4 : User Interface














Screen 5: - Downloading Files as Archieve


//HRML Mark Up
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DownloadFilesinZipFormat.aspx.cs" Inherits="DownloadFilesinZipFormat" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            font-family: "Bookman Old Style";
            font-size: large;
        }
    </style>
</head>
<body style="text-align: center">
    <form id="form1" runat="server" class="style1">
    Sample Project for downloading Files in ZIP Format<p>
        <asp:FileUpload ID="xfuupload" runat="server" /> <br /><br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" 
            onclick="btnUpload_Click" />
    </p>
    <p>
        <asp:Literal ID="xlit" runat="server"></asp:Literal>
    </p>
    <div align="center">
        <asp:GridView ID="xfiles" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Select Files">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkselectfordownload" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Text" HeaderText="Files" />
            </Columns>
        </asp:GridView>
        <br />
        <br />
        <asp:Button ID="btnDownload" runat="server" Text="Download Selected Files" 
            onclick="btnDownload_Click" />
    
    </div>
    
    </form>
</body>
</html>
// Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Ionic.Zip;


public partial class DownloadFilesinZipFormat : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Calling the function of Grid View Bind
            BindGridview();
        }
    }

    protected void BindGridview()
    {
        // Creation of String arrary to store path
        string[] getfilesPath = Directory.GetFiles(Server.MapPath("~/FilesUploaded/"));
        // Adding files to list
        List<ListItem> files = new List<ListItem>();
        foreach (string path in getfilesPath)
        {
            //Adding files to the list item
            files.Add(new ListItem(Path.GetFileName(path)));
        }
        xfiles.DataSource = files;
        xfiles.DataBind();
    }


    protected void btnUpload_Click(object sender, EventArgs e)
    {
        // Uploading the Files to the folder
        if (xfuupload.HasFile)
        {
            string filename = Path.GetFileName(xfuupload.PostedFile.FileName);
            xfuupload.SaveAs(Server.MapPath("FilesUploaded/") + filename);
            xlit.Text = "File Uploaded Successfully";
            BindGridview();
        }
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        // Creating an Object of ZipFile Class in Iconic.Zip dll
        ZipFile creatingzip = new ZipFile();
        //Finding the Checkbox Control and checking which of the files are selected using the check box
        foreach (GridViewRow gvrow in xfiles.Rows)
           {
        CheckBox chk = (CheckBox) gvrow.FindControl("chkselectfordownload");
            if(chk.Checked)
                {
                    string fileName= gvrow.Cells[1].Text ;
                    string filePath = Server.MapPath("~/FilesUploaded/" + fileName);
                    // Adding the file to Zip Archieve
                    creatingzip.AddFile(filePath, "files");
                 }
         }
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=Downloads.zip");
                    // Setting the content type to ZIP
                    Response.ContentType = "application/zip";
                    creatingzip.Save(Response.OutputStream);
                    Response.End();
        }
    }
The Iconic Zip Dll is useful not only to download files from GridView but you can create an Archive on the fly by selecting the files.


Reference


Methods understood from :- http://dotnetzip.codeplex.com/

Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)