Click to See Complete Forum and Search --> : Problem with “Response.BinaryWrite”


paradise_wolf
04-01-2007, 07:27 PM
It seems that the download dialog triggered by this code
prevents the label control “Label2” to show its message.

What should I change/add to this code in order that the
"path" could appear in the web page in the
“Label2” control ?


Here is the relevant code:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

protected void DownlFile_Click(object sender, EventArgs e)
{


string web_path = "./items/X-103.pdf";

string path = Server.MapPath(web_path);

Label2.Text = path;

FileStream MyFileStream = new FileStream(path, FileMode.Open);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
Response.ContentType = "application/pdf";

Response.AddHeader
("content-disposition", "attachment; filename= X-103.pdf");

Response.BinaryWrite(Buffer);



}

<asp:Button ID="DownlFile" runat="server" Text="Download The File"
OnClick="DownlFile_Click" />
<br /> <br />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>

Cstick
04-01-2007, 10:40 PM
You can't set the label and send the file during the same request. With your code the way it is, download the PDF and open it in Notepad, then scroll to the bottom... Do you see HTML text at the bottom?

What is happening is that you are loading the byte array from the file into the response stream and then page is rendering the HTML into the response stream. Due to the nature of PDF's specs, everything past the closing lines of code is ignored and that's why the PDF viewer doesn't complain about a corrupt PDF.

The browser never refreshes the HTML because the response header specifies that a file is being returned instead. So, without doing anything fancy like opening a new page which downloads the file or something similar, you can't set the label and download the file on the same request.

Another little note, when the save dialog comes up, does it not have the same filename you specified in your code? I've found that spaces in the "content-disposition" header can cause undesirable results.

BTW, to get rid of the HTML at the bottom of the PDF and have the filename be correct, your last bit of code will look like this instead:

FileStream MyFileStream = new FileStream(path, FileMode.Open);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
Response.ContentType = "application/pdf";

Response.AddHeader
("content-disposition", "attachment;filename=X-103.pdf"); //this fixes the filename

Response.BinaryWrite(Buffer);
Respones.End(); //this stops the html by closing the response stream.

paradise_wolf
04-02-2007, 05:13 AM
Thank you, Cstick.