I'm writing a simple test page to download a text file from a browser on button click. I am getting a really strange error that I have never seen before. Any thoughts?
The error occurs 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.
ASP.NET provides implicit object Response and its methods to download file from the server. We can use these methods in our application to add a feature of downloading file from the server to the local machine.
In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With