0

I am having trouble getting a file to be sent to the browser for download prompt. I simply want a button that when pressed, prompts the user to download a .csv file. I have a method to do this, but when I press the button nothing happens at all. I have put breakpoints in the method and it IS being called and run, but no prompt ever occurs. It's as though the button is not attached to anything.

Here is the method (it doesn't currently write the actual csv data just the header, I just want to get it to where it prompts)

protected void btnExport_Click(object sender, EventArgs e)
{

    using (StringWriter sw = new StringWriter())
    {
        sw.WriteLine("sep=|");//define separator
        sw.WriteLine("WHY|WONT|THIS|WORK");//header row

        //create responce
        Response.ClearHeaders();
        Response.ClearContent();
        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=Participants.csv");
        Response.ContentType = "text/csv";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
        Response.Write(sw); //write response body
                            //Response.End();
        Response.Flush();//push it out
        Response.SuppressContent = true;
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }
}
Sveniat
  • 51
  • 7

2 Answers2

1

I don't think you should have SuppressContent there.

Try the following:

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Participants.csv");
Response.ContentType = "text/csv";
Response.OutputStream.Write(sw);
Response.OutputStream.Flush();
Response.End();
Richard
  • 29,854
  • 11
  • 77
  • 120
  • That doesn't work either. I think it may be an environment thing. Is there a property on the button maybe that is causing it not to prompt the user? – Sveniat Jan 19 '16 at 20:53
  • Is the button code running? Use your browser's dev tools to look at what happens when you click the button. – Richard Jan 19 '16 at 21:02
  • I have put breakpoints in the method, and they correctly halt the program when i click the button, so the button code is correctly being called on the click event. – Sveniat Jan 19 '16 at 21:14
0

Turns out the code in question was in an asynchronous postback, and you can't use Response.Flush() during an asynchronous postback.

The solution was found on this page: Response.Write and UpdatePanel

Community
  • 1
  • 1
Sveniat
  • 51
  • 7