When downloading a file from ASP .Net, the text file gets appended with HTML content

旧街凉风 提交于 2019-11-30 21:32:25

Make sure to end your Response by calling Response.End() after Response.WriteFile(filepath) or else your form will be appended to the stream and sent to the client.

It will affect other files as well though most likely only be seen as garbage at the end of the file and ignored by their respective applications.

Shoaib Qureshi

Is is not safe to use Response.End(), It will always return a System.Threading.ThreadAbortException:.. if debugged and seen in the catch block...

Alternative.. Use the following instead...

Response.Flush();
Response.SuppressContent = true;
Response.WriteFile(filepath);
HttpContext.Current.ApplicationInstance.CompleteRequest();

Response.redirect threw an exception. Shoaib's answer got me closer but it suppressed everything including the valid file content. What worked for me was reordering the statements as follows:

 Response.ContentType = ContentType
 Response.AppendHeader("Content-Disposition", "attachment; filename=" & originalFileName)
 Response.WriteFile(filePath)
 Response.Flush()
 Response.SuppressContent = True
 HttpContext.Current.ApplicationInstance.CompleteRequest()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!