Search code examples
c#httphandler

Dowloading a .zip directory with HttpHandler


I'm currently having troubles with HttpHandler (first time using it). Basically I'm generating a .zip folder on the fly for download purposes. I'm passing a ID (generated with Guid) to my handler to check if the folder exists and either download it or throw an exception.

As far as I understood, using a handler should do the job but I can't manage to get my head in this mess. Here follows the code I've written so far, first the call to the handler, then the handler itself

<a href="MyHandler.ashx?requestID=@requestID" target="_blank">


<%@ WebHandler Language="C#" Class="MyHandler" %>

using System;
using System.Web;
using System.IO;
using System.Web.Hosting;

public class MyHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        var id = context.Request.QueryString["requestID"];
        var dirPath = new DirectoryInfo(Path.Combine(HostingEnvironment.MapPath("~/App_Data/") + id + ".zip"));

        if (dirPath.Exists)
        {
            context.Response.ContentType = "application/octet-stream";
            context.Response.AppendHeader(HostingEnvironment.MapPath("~/App_Data/"), "attachment;filename=" + id+".zip");            
        } 
        else
            throw (new HttpException("404"));
    }

    public bool IsReusable
    {
        get { return false; }
    }

}

I just need to download this .zip directory. When opening the dynamically generated error I get a 404 error, but the directory is correctly created and zipped. Am I using the wrong method?


Solution

  • You could just use WebClient for a 2-liner:

    using(Webclient wc = new WebClient())
    { 
       wc.DownloadFile(url, @"D:\downloads\1.zip");
    }