ASP.Net Download file to client browser

让人想犯罪 __ 提交于 2019-11-26 04:49:18

问题


I\'m writing a simple test page to download a text file to a browser on button click. I am getting a really strange error that I have never seen before. Any thoughts?

The error occures on \'Response.End();\' and the file never gets to the client browser

Code:

  string filePath = \"C:\\\\test.txt\";
  FileInfo file = new FileInfo(filePath);
  if (file.Exists)
  {
    Response.ClearContent();
    Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + file.Name);
    Response.AddHeader(\"Content-Length\", file.Length.ToString());
    Response.ContentType = \"text/plain\";
    Response.TransmitFile(file.FullName);
    Response.End();
  }

Error:

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.


回答1:


Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();



回答2:


Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.



来源:https://stackoverflow.com/questions/8897458/asp-net-download-file-to-client-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!