以下是创建CSV文件后的代码,我想要下载这个文件,所以使用了下面的代码。但是它会在“Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV + "\"");"处抛出错误“服务器无法在HTTP头已发送之后附加头”。它正在下载,但浏览器没有重定向到同一页。
代码如下:
string[] header = { "Error Occurred On", "Controller Name", "Action Name", "Exception Occurred", "Stack Trace Description", "InnerException Occurred", "Stack Trace InnerException Occurred " };
代码如下:
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-Length", bytes.Length.ToString());
Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}