Responding with a csv file in asp.net

11,150

Solution 1

The following code worked for me. You may just be missing a file extension.

Response.Clear();
Response.ContentType = "text/csv";
Response.AppendHeader("Content-Disposition",
                string.Format("attachment; filename={0}.csv", DateTime.Now));
Response.Write(TextBox_Data.Text);
Context.Response.End();

Solution 2

Just a complement on joshb's answer regarding the use of Response.End():

MSDN does not recommend the use of Response.End() for non-error cases, and in some cases it can actually cause the client to lose some data .

In my case sometimes the downloaded csv would loose the last bytes of the last line, so I removed the Response.End() and used

    HttpContext.Current.ApplicationInstance.CompleteRequest()

instead, and I had to override the page's Render(HtmlTextWriter writer) method to not write anything on the request, since the csv was already writen.

public class PageBase : Page
{
    private bool performRegularPageRender = true;

    protected override void Render(HtmlTextWriter writer)
    {
        if (performRegularPageRender)
            base.Render(writer);
    }

    public void SkipRegularPageRendering()
    {
        performRegularPageRender = false;
    }
}

More info / credits: msdn blog; Is Response.End() considered harmful?; PostBack and Render Solutions? Overrides

Share:
11,150
Peter Rasmussen
Author by

Peter Rasmussen

Who doesn't want to create the right solutions, at the right time? My favourite tags: C#, Java, Javascript, Html, Css. Feel free to contact me outside stack overflow: Blog | Twitter | Careers profile

Updated on June 26, 2022

Comments

  • Peter Rasmussen
    Peter Rasmussen almost 2 years

    I am trying to make a csv file from a textbox and then send it to the user. This is my code so far:

    Response.Clear();
                Response.ContentType = "text/csv";
                Response.AppendHeader("Content-Disposition",
                    string.Format("attachment; filename={0}", DateTime.Now));
    
                Response.Write(TextBox_Data.Text);
                Context.Response.End();
    

    What is sent is an empty xml file, I have never tried responding with a file before and I'm wondering why it does this?

    I have also tried the following which did not work:

    var writer = File.CreateText("C:\\file.csv");
                writer.WriteLine(TextBox_Data.Text);
    
                Context.Response.Clear();
                Context.Response.AppendHeader("content-disposition", "attachment; filename=" + DateTime.Now + ".csv");
                Context.Response.ContentType = "text/csv";
                Context.Response.Write("C:\\file.csv");
                Context.Response.Flush();
                Context.Response.End();
    

    Let me know if you have the answer :)