Search code examples
c#asp.netcsvexport-to-csvihttphandler

Download csv file via HTTP handler


I got error using HttpContext.Current.Response.End(); when try to download csv file. I search for error and get solution . Use Handler to avoid Response.End();.

My handler :

public class DownloadHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string table = HttpContext.Current.Request.QueryString["table"].ToString();
        string fileName = HttpContext.Current.Request.QueryString["fileName"].ToString();
        table = table.Replace(">", ">");
        table = table.Replace("&lt;", "<");
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".csv");
        HttpContext.Current.Response.ContentType = "application/text";
        HttpContext.Current.Response.Write(table);

    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

I call this handler in button click like this.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Mypath/DownloadHandler.ashx?table=" + csv + "&fileName=User-Report");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Its call the handler .I have no error but csv file is not downloaded ? I am unable to figure out where is a real problem. May I missing something in code ? Thanks for help.

Note: csv is a string comes from another process that's not a real problem.


Solution

  • If you are doing HttpWebRequest then you have to request then getResponse. Read from response stream and save.

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:57169/DownloadHandler.ashx?table=tttex&fileName=User-Report");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            byte[] data = new System.IO.BinaryReader(response.GetResponseStream()).ReadBytes((int)response.ContentLength);
            System.IO.File.WriteAllBytes("C:\\Temp.csv", data);
    

    if you want browser to download then just do following thing.

      Response.Redirect("http://yourpath/DownloadHandler.ashx?table=tttex&fileName=User-Report");