Saturday, May 18, 2013

HTML source code wrongly appended to streamed file using Response.Write

Today while writing a small web application where I needed to download a datatable as csv file. I faced issue of page html getting wrongly appended to file being downloaded. I was using Response.Write to download file on client machine.

Solution to my problem was easy, I just needed to add an extra line telling content-length. Below is method that I finally ended up using.


        private void DownloadDataAsCsv(DataTable dt)
        {
            string tab = "";
            StringBuilder sb = new StringBuilder();
            foreach (DataColumn dc in dt.Columns)
            {
                sb.Append(tab + dc.ColumnName);
                tab = ",";
            }
            sb.Append("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(tab + dr[i].ToString());
                    tab = ",";
                }
                sb.Append("\n");
            }
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition", "attachment; filename=Export.csv");
            Response.AddHeader("Content-Length", sb.ToString().Length.ToString());
            Response.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }

About Me

My photo
Delhi, India
Fun, music, travel and nature loving, always smiling, computer addict!!