23

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.

2
  • 1
    remove the end, and try the Responce.Flush() and the Responce.ApplicationInstance.CompleteRequest(); Commented Jan 17, 2012 at 15:46
  • Good call, that stopped the exception from being thrown. But the code still completes without anything happening on the browser. ?? Commented Jan 17, 2012 at 15:55

2 Answers 2

40

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(); 
Sign up to request clarification or add additional context in comments.

7 Comments

Same as before, runs through the code and throws an exception on Response.End(). It seems weird that Response.TransmitFile executes ok but the file does not get transfered?
@Ashwin: I'm trying this solution in my code-behind file (my issue is stackoverflow.com/questions/18599735/downloading-a-dynamic-file), but no matter where I attempt to call TransmitFile() or WriteFile() I keep getting an exception: Server cannot set content type after HTTP headers have been sent. Any suggestions?
Response.End() throws an exception by nature.
This worked for our application which uses this method to allow users to download .svg files.
Response.Clear(); does the same as Response.ClearContent(); Why have both?
|
8

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.