C# – Server cannot append header after HTTP headers have been sent

asp.net-mvccmodel-view-controller

Below shown is my code after creating the CSV file, i want to download the file so i am using below code. but its throwing error " Server cannot append header after HTTP headers have been sent" at "Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV + "\"");" place. Its downloading but browser not redirecting to 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-Length", bytes.Length.ToString());
    Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV);
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

Best Answer

You cannot redirect after downloading the File, you are attempting to perform 2 actions where you can only do the first.

I suggest that you download the file in a new (popup) window and redirect the main page if required.

Edit:-

You could force the download by opening the file-download action using window.open.

Example:-

<a href="Action/RedirectPage" data-file="Action/DownloadCVS" class="file-download">Download File</a>

<script>
  $(function() {
      $('a.file-download').click(function() {
         window.open($(this).data('file'));
      }); 
  });
</script>
Related Topic