10

In my application user can download a file after clicking a link. Document is PDF/RTF generated in code. I use:

byte[] downloadBytes = some pdf document bytes...
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
                "attachment; filename=filename.pdf; size=" + downloadBytes.Length.ToString()); 
response.Flush();
response.BinaryWrite(downloadBytes);
response.Flush();
response.End();

It works OK but is this generally a good way ? Why flush is called two times? I found many different examples and this one works fine but sometimes I got The remote host closed the connection. The error code is 0x80070057 error. I found solution that I should use

if (Response.IsClientConnected)
{
     Response.Flush();
     Response.End();
}

How the entire code should look like?

jlp
  • 9,800
  • 16
  • 53
  • 74

2 Answers2

4

Here is the code that I use. It does not call flush at all. I am not sure if it is the right way, but it works for me.

public static void ResponseOpenFileBytes(byte[] File, string ContentType, string SaveAsFileName, HttpResponse response)
{
    if (string.IsNullOrEmpty(ContentType))
    {
        ContentType = "application/octet-stream";
    }

    response.Clear();
    response.AddHeader("content-disposition", "attachment;filename=" + SaveAsFileName);
    response.ContentType = ContentType;
    response.BinaryWrite(File);
    response.End();
}
Chris Mullins
  • 6,677
  • 2
  • 31
  • 40
2

I don't see why you should call Flush() two times. One is enough, after calling BinaryWrite().

The first call to Flush() sends the headers to the browser, including Content-Length, which is still unknown at the time of the call - or simply wrong.

Also, I would avoid calling End() unless it's absolutely necessary.

Dario Solera
  • 5,694
  • 3
  • 29
  • 34
  • the first call is probably intended to make sure the headers are sent before the file body - probably overkill, but might make a difference for large files. – Nathan May 05 '11 at 09:56
  • Actually, that might be the problem because the headers have been sent already and Content-Length was already set (to zero?). I'll update my answer. – Dario Solera May 05 '11 at 10:15