Download txt file with ASP.NET Web Forms including page HTML in file

2

I am downloading files with ASP.NET Web Forms in the click event of a LinkButton as follows:

var file = new FileInfo(filePath);

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.Name));
Response.AddHeader("Content-Length", file.Length.ToString(CultureInfo.InvariantCulture));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);

The code works, however when the file is a .txt it, in addition to its original content, comes with all the HTML of the current page. Does anyone know how to solve this?

    
asked by anonymous 31.03.2015 / 20:06

1 answer

2

You're probably running some code even after typing the file into output.

Use the Response.Flush method to ensure that the file is written to Stream of response, and then call Response.End to finish with any subsequent code.

var file = new FileInfo(filePath);

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename="
                                          + HttpUtility.UrlEncode(file.Name));
Response.AddHeader("Content-Length", file.Length.ToString(CultureInfo.InvariantCulture));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
    
31.03.2015 / 20:31