My code is shown below after creating the CSV file, I want to download the file, so I use the code below. but his throwing error "Server cannot add a header after sending HTTP headers" in "Response.AddHeader" ("Content-disposition", "attachment; filename =" + fileCSV + "\" ";" place. Its loading, but the browser is not redirecting to the same page.
string[] header = { "Error Occurred On", "Controller Name", "Action Name", "Exception Occurred", "Stack Trace Description", "InnerException Occurred", "Stack Trace InnerException Occurred " };
The code:
DataTable dt = new DataTable();
for (int e = 0; e < header.Length; e++)
{
dt.Columns.Add(header[e], typeof(string));
}
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
dt.DefaultView.RowFilter = "[Exception Occurred] LIKE '%" + keyword + "%'";
DataTable dtFilter = new DataTable();
dtFilter = dt.DefaultView.ToTable();
foreach (DataRow row in dtFilter.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
System.IO.File.WriteAllText(fileCSV, sb.ToString());
byte[] bytes = Encoding.ASCII.GetBytes(sb.ToString());
if (bytes != null)
{
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
source
share