Arindam Das
Arindam Das

Reputation: 699

why i am not getting the .csv file in my asp.net application using c#?

i am trying to get a .csv file on client machine by a click of a button by this code:

Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "text/csv"; ;
    Response.ContentEncoding = System.Text.Encoding.Unicode;
    Response.AddHeader("Content-Disposition", "attachment; filename=WBS.csv");
    Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
    string output = "WBSCode,Description,TerritoryCode,Amount" + "\n";
    Response.Write(output);

the problem is the code is executing but i am not getting a .csv file in my machine.. what is the problem ? i am doing this for the 1st time

Upvotes: 1

Views: 1032

Answers (1)

g45rg34d
g45rg34d

Reputation: 9660

You need to create a generic handler (.ashx file), which will send the csv as response. Your button then simply needs to have a url to that .ashx. Below is the example of the handler with some of your code.

public class GetCsvFile : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/csv";
        context.Response.AddHeader("Content-Disposition", "attachment; filename=WBS.csv");
        context.Response.Write("WBSCode,Description,TerritoryCode,Amount\n");
    }

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

Upvotes: 4

Related Questions