tier1 tier1 - 2 months ago 35
ASP.NET (C#) Question

ASP.Net Download file to client browser

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.

Answer

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();
Comments