Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Download file to client browser

Tags:

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.

like image 251
tier1 Avatar asked Jan 17 '12 15:01

tier1


People also ask

What is asp net download file?

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.

How do I download files from Web API?

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.


2 Answers

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();
like image 150
Ashwin Chandran Avatar answered Sep 22 '22 22:09

Ashwin Chandran


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.

like image 26
EMalik Avatar answered Sep 23 '22 22:09

EMalik