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

3
  • 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. Commented Jun 22, 2012 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 Commented Jun 22, 2012 at 15:23
  • 1
    Look into Response.BinaryWrite so you can skip the extra overhead from writing/reading the file from disk. Commented Jun 22, 2012 at 16:57

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

</ContentTemplate> <Triggers> <asp:PostBackTrigger ControlID="btnDownload" /> </Triggers> </asp:UpdatePanel>
0

I'm pretty sure you need

Response.Write()

after

Response.End()

1 Comment

Really? What would I be response.writing, as it would need a string or object?
0

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

    Response.ClearContent();
    Response.ClearHeaders(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.