ASP.Net将文件下载到客户端浏览器

tie*_*er1 19 browser asp.net response.write download

我正在编写一个简单的测试页面,通过点击按钮将文本文件下载到浏览器.我得到了一个我从未见过的非常奇怪的错误.有什么想法吗?

'Response.End();'发生错误 并且文件永远不会到达客户端浏览器

码:

  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();
  }
Run Code Online (Sandbox Code Playgroud)

错误:

无法计算表达式,因为代码已优化或本机帧位于调用堆栈之上.

小智 36

尝试将其更改为.

 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();
Run Code Online (Sandbox Code Playgroud)


Nas*_*she 8

如果您遇到下载文件名称的问题,只需对上述解决方案稍加补充......

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
Run Code Online (Sandbox Code Playgroud)

这将返回确切的文件名,即使它包含空格或其他字符.