0

I have already saved csv file as /Exports/test.csv. I want to allow user to download file on button click . I have create a handler for that code is as :

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

using System;
using System.Web;
using System.Net;

public class Downloadfile : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Clear();

        context.Response.ContentType = "text/csv";
        context.Response.AddHeader("Content-Disposition", 
            "attachment; filename=" + context.Request.QueryString["file"]);

        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

Above code download the file but its empty. I want just download csv file with its content.

1
  • 2
    So your response header says there is a file in the response, but you don't actually send the file. Commented Mar 11, 2013 at 17:38

2 Answers 2

3

You need to transmit file. You can do that by using TransmitFile method or instead of write to disk you can just write directly to context.Response.OutputStream.

public void ProcessRequest(HttpContext context)
{
    context.Response.ClearHeaders();
    context.Response.Clear();
    context.Response.ContentType = "text/csv";
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" +  context.Request.QueryString["file"]);
    context.Response.TransmitFile("/Exports/test.csv");
    context.Response.End();
}
Sign up to request clarification or add additional context in comments.

1 Comment

it works what show the downloaded file content as: ‹ I-.QÈMÌÓQ±Âól š÷Æ and actual is "Test man, Test Woman"
3

I actually had to do the same thing the other day, depending on what the users pass in the "Accepts" header. I used the example from the MSDN article on Media Formatters, and it worked perfectly.

Mine was a bit different from yours since I'm using MVC's WebApi, but the underlying concepts are the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.