views:

205

answers:

1

After building a filepath (path, below) in a string (I am aware of Path in System.IO, but am using someone else's code and do not have the opportunity to refactor it to use Path). I am using a FileStream to deliver the file to the user (see below):

FileStream myStream = new FileStream(path, FileMode.Open, FileAccess.Read);  
long fileSize = myStream.Length;  
byte[] Buffer = new byte[(int)fileSize + 1];  
myStream.Read(Buffer, 0, (int)myStream.Length);  
myStream.Close();  
Response.ContentType = "application/csv";  
Response.AddHeader("content-disposition", "attachment; filename=" + filename);  
Response.BinaryWrite(Buffer);  
Response.Flush();  
Response.End();

I have seen from: http://stackoverflow.com/questions/736301/asp-net-how-to-stream-file-to-user reasons to avoid use of Response.End() and Response.Close(). I have also seen several articles about different ways to transmit files and have diagnosed and found a solution to the problem (https and http headers) with a colleague.

However, the error message that was being displayed was not about access to the file at path, but the aspx file.

Edit: Error message is:

Internet Explorer cannot download MyPage.aspx from server.domain.tld

Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later. (page name and address anonymised)

Why is this? Is it due to the contents of the file coming from the HTTP response .Flush() method rather than a file being accessed at its address?

+1  A: 

Even though you are sending a file, it is the "page" that contains the header information that describes the file you are sending. The browser still has to download that page, then sees the "attachment; filename=" and gives you the file instead.

So if there is an error, it will be page that is shown as the problem. It's a bit like getting a corrupted email with an attachment, you seen the problem in the email not the attachment itself.

Don't call Response.End();

cdm9002