ASP.NET (C#)

DotNetZip

DotNetZip - ASP.NET Example in C#

ASP.NET Example in C#

Here's an Example ASP.NET page, using C#, that dynamically creates a zip file and saves it to Response.OutStream. From the browser, the user will be prompted with the familiar download dialog box, allowing Open, Save, or Cancel of the generated zip file.

CopyASP.NET example in C#
  1<%@ Page
  2    Language="C#"
  3    Debug="true" %>
  4
  5<%@ Import Namespace="System.Text" %>
  6<%@ Import Namespace="System.IO" %>
  7<%@ Import Namespace="Ionic.Zip" %>
  8<%@ Import Namespace="System.Collections.Generic" %>
  9
 10<script language="C#" runat="server">
 11
 12// ZipExample.aspx
 13// 
 14// This .aspx page demonstrates how to use the DotNetZip library from within ASP.NET.
 15// 
 16// To run it,
 17//  1. drop the Ionic.Zip.dll into the \bin directory of your ASP.NET app
 18//  2. create a subdirectory called "fodder" in your web app directory.
 19//  3. copy into that directory a variety of random files.
 20//  4. insure your web.config is properly set up (See below)
 21// 
 22// 
 23// notes:
 24//  This requies the .NET Framework 3.5 - because it uses the ListView control that is
 25//  new for ASP.NET in the .NET Framework v3.5.
 26// 
 27//  To use this control, you must add the new web controls.  Also, you must use the v3.5 compiler.
 28//  IF you build your app in Visual Studio, this is all done for you. If you don't use VS2008,
 29//  here's an example web.config that works with this aspx file:
 30// 
 31//    <configuration>
 32//      <system.web>
 33//        <trust level="Medium" />
 34//        <compilation defaultLanguage="c#" />
 35//        <pages>
 36//          <controls>
 37//            <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
 38//          </controls>
 39//        </pages>
 40//      </system.web>
 41//      <system.codedom>
 42//        <compilers>
 43//          <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
 44//            <providerOption name="CompilerVersion" value="v3.5" />
 45//            <providerOption name="WarnAsError" value="false" />
 46//          </compiler>
 47//        </compilers>
 48//      </system.codedom>
 49//    </configuration>
 50// 
 51// 
 52// 
 53
 54
 55public String width = "100%";
 56
 57public void Page_Load (Object sender, EventArgs e)
 58{
 59    try
 60    {
 61        if ( !Page.IsPostBack ) {
 62            // populate the dropdownlist
 63            // must have a directory called "fodder" in the web app
 64            String homeDir = Server.MapPath(".");
 65            String sMappedPath= Server.MapPath("fodder");
 66
 67            var fqFilenames= new List<String>(System.IO.Directory.GetFiles(sMappedPath));
 68            var filenames= fqFilenames.ConvertAll((s) => { return s.Replace(sMappedPath+"\\", ""); });
 69
 70            ErrorMessage.InnerHtml = "";
 71
 72            FileListView.DataSource = filenames;
 73            FileListView.DataBind();
 74        }
 75
 76    }
 77    catch (Exception)
 78    {
 79        // Ignored
 80    }
 81}
 82
 83
 84public void btnGo_Click (Object sender, EventArgs e)
 85{
 86    ErrorMessage.InnerHtml ="";   // debugging only
 87    var filesToInclude= new System.Collections.Generic.List<String>();
 88    String sMappedPath= Server.MapPath("fodder");
 89    var source= FileListView.DataKeys as DataKeyArray ;
 90
 91    foreach (var item in  FileListView.Items)
 92    {
 93        CheckBox chkbox= item.FindControl("include") as CheckBox ;
 94        Label lbl= item.FindControl("label") as Label ;
 95
 96        if (chkbox!=null  && lbl != null)
 97        {
 98            if (chkbox.Checked)
 99            {
100                ErrorMessage.InnerHtml += String.Format("adding file: {0}<br/>\n", lbl.Text);
101
102                filesToInclude.Add(System.IO.Path.Combine(sMappedPath,lbl.Text));
103            }
104        }
105    }
106
107    if (filesToInclude.Count==0)
108    {
109        ErrorMessage.InnerHtml += "You did not select any files?<br/>\n";
110
111    }
112    else
113    {
114        Response.Clear();
115
116        System.Web.HttpContext c= System.Web.HttpContext.Current;
117        String ReadmeText= String.Format("README.TXT\n\nHello!\n\n"+
118                                         "This is a zip file that was dynamically generated at {0}\n"+
119                                         "by an ASP.NET Page running on the machine named '{1}'.\n"+
120                                         "The server type is: {2}\n",
121                                         System.DateTime.Now.ToString("G"),
122                                         System.Environment.MachineName,
123                                         c.Request.ServerVariables["SERVER_SOFTWARE"]
124                                         );
125        string archiveName= String.Format("archive-{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
126        Response.ContentType = "application/zip";
127        Response.AddHeader("content-disposition", "filename=" + archiveName);
128
129        using (ZipFile zip = new ZipFile())
130        {
131            foreach (var f in filesToInclude)
132            {
133                zip.AddFile(f, "files");
134            }
135            zip.AddEntry("Readme.txt", ReadmeText);
136            zip.Save(Response.OutputStream);
137        }
138        Response.Close();
139    }
140
141}
142
143</script>
144
145
146
147<html>
148  <head>
149    <link rel="stylesheet" href="style/basic.css">
150  </head>
151
152  <body>
153
154    <form id="Form" runat="server">
155
156      <h3> <span id="Title" runat="server" />Zip Files from ASP.NET </h3>
157
158      <p>This page uses the .NET Zip library
159      (see <a href="http://www.codeplex/com/DotNetZip">http://www.codeplex/com/DotNetZip</a>)
160       to dynamically create a zip archive, and then download it to the browser through Response.OutputStream</p>
161
162      <span class="SampleTitle"><b>Check the boxes to select the files, then click the button to zip them up.</b></span>
163      <br/>
164      <br/>
165      <asp:Button id="btnGo" Text="Zip checked files" AutoPostBack OnClick="btnGo_Click" runat="server"/>
166
167      <br/>
168      <br/>
169      <span style="color:red" id="ErrorMessage" runat="server"/>
170      <br/>
171
172      <asp:ListView ID="FileListView" runat="server">
173
174        <LayoutTemplate>
175          <table>
176            <tr ID="itemPlaceholder" runat="server" />
177          </table>
178        </LayoutTemplate>
179
180        <ItemTemplate>
181          <tr>
182            <td><asp:Checkbox ID="include" runat="server"/></td>
183            <td><asp:Label id="label" runat="server" Text="<%# Container.DataItem %>" /></td>
184          </tr>
185        </ItemTemplate>
186
187        <EmptyDataTemplate>
188          <div>Nothing to see here...</div>
189        </EmptyDataTemplate>
190
191      </asp:ListView>
192
193
194    </form>
195
196  </body>
197
198</html>