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

Asked

Viewed 1,887 times

2

I am downloading files with ASP.NET Web Forms at a Linkbutton click event 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, but when the file is a .txt the same, in addition to its original content, comes with all the HTML of the current page. Someone knows how to solve this?

  • This is ASP.NET MVC, Webforms, Webapi... could post more details of the context in which you are running the code you specified?

  • @I edited the question.

1 answer

2


You are probably running some code even after writing the file in output.

Use the method Response.Flush to ensure the writing of the Stream reply, and then call Response.End to terminate at once 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();
  • I only used the Response.End method and it worked, as you said, something is probably running after the method call, I’ll see if I can find out what it is...

  • Since the method is run on the server via post, could it be adding the contents of the file to the content of Sponse and because it is text, it is including html, since the page is rendered again? Makes sense?

  • Full sense. Webforms has a life cycle very complex, so depending on where exactly the above code is, within this cycle, the next steps of the cycle would be executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.