Responding with a csv file in asp.net

2019-05-10 03:24发布

问题:

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 :)

回答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();


回答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