Tuesday, September 8, 2015

When I try to make the browser cough out a .txt file as if said file were being downloaded, the copy inside gets the HTML of the current page appended after the real copy I want to include.

In C# your code for as much might look like so:

byte[] bytes = File.ReadAllBytes(pathToFlatFile);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=foo.txt";
HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
HttpContext.Current.Response.Flush();

 
 

This suggests that the solution is to chase the lines above with:

HttpContext.Current.Response.End();

 
 

...but I put the line with the .End(); immediately before the line with the .Flush(); and that seemed to work too!

No comments:

Post a Comment