Export datatable to CSV using Save File dialog box - C #

Struggling to get the CSV export to display the Save File dialog box up. It saves the file in order, but does not allow the user to save. Can someone see where I might go 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 brought up a dialog box, but maybe I need to do something else.

thanks

0
source share
3 answers

And we found out what the problem is ...

I have a button on the update panel and I don’t understand that the response object does not work on the update panel.

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

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

Thanks for the suggestions anyway

+2
source

I'm sure you need

 Response.Write() 

after

 Response.End() 
0
source

You can try to clear the contents and headers after calling Response.Clear() :

  Response.ClearContent(); Response.ClearHeaders(); 
0
source

Source: https://habr.com/ru/post/1446377/


All Articles