问题
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