0

Struggling to get my CSV export to display the Save File dialog box up. It saves to file ok, but doesn't let the user save. Can anybody see where I might be going wrong with the code please?

string filename = Server.MapPath("~/download.csv");
StreamWriter sw = new StreamWriter(filename, false);

int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
    sw.Write(dt.Columns[i]);
    if (i < iColCount - 1)
    {                
        sw.Write(",");
    }
}
sw.Write(sw.NewLine);

foreach (DataRow dr in dt.Rows)
{
    for (int i = 0; i < iColCount; i++)
    {
        if (!Convert.IsDBNull(dr[i]))
        {
            sw.Write(dr[i].ToString());
        }
        if (i < iColCount - 1)
        {
            sw.Write(",");
        }
    }
    sw.Write(sw.NewLine);
}
sw.Close();

Response.Clear();
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv");
Response.WriteFile(filename);
Response.Flush();
Response.End();

I thought the Content Disposition line that brought up the dialog box, but maybe there is something else I need to do.

Thanks

e-on
  • 1,547
  • 8
  • 32
  • 65
  • Do you need to save the file? Or do you just want to serve it? Also, your CSV writing algo is weak and doens't take into account multi line or commas in values. – banging Jun 22 '12 at 15:18
  • Hi, no I don't need to save the file - happy just to serve it. The algo is basic, because that's all it needs - the data that will be getting exported is very basic - about 8 columns, either dates, bools or single words – e-on Jun 22 '12 at 15:23
  • 1
    Look into Response.BinaryWrite so you can skip the extra overhead from writing/reading the file from disk. – banging Jun 22 '12 at 16:57

3 Answers3

2

Ah, have discovered what the problem is...

I've got the button in an update panel and didn't realise the response object doesn't work in an update panel.

I made the download button a trigger, and it now works great.

<Triggers>
    <asp:PostBackTrigger ControlID="btnDownload" />
</Triggers>

Thanks for the suggestions anyway

e-on
  • 1,547
  • 8
  • 32
  • 65
0

I'm pretty sure you need

Response.Write()

after

Response.End()
Eric Robinson
  • 2,025
  • 14
  • 22
0

You could try clearing the content and the headers after your Response.Clear() call:

    Response.ClearContent();
    Response.ClearHeaders(); 
DaveB
  • 9,470
  • 4
  • 39
  • 66