Thursday, March 22, 2012

Why the file gets corrupted with this downloading code ?

Why, after downloading the file with the below code,

I amgetting this message from Acrobat Reader

program:

"Acrobat could not open 'VZ-332.pdf' because it is

either not a supported file type or because the file has

been damaged..."

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

privateconstint BUFFER_SIZE = 32768;

protectedvoid DownlFile_Click(object sender,EventArgs e)

{

string web_path ="./items/VZ-332.pdf";

string path = Server.MapPath(web_path);

Response.Buffer =false;

Response.BufferOutput =false;

Response.ContentType ="application/pdf";

Response.AddHeader("Content-Disposition",

"attachment;filename=VZ-332.pdf");

Stream outstream = Response.OutputStream;

FileStream instream =newFileStream(path,

FileMode.Open,FileAccess.Read,FileShare.Read);

//#######################################

long FileSize = instream.Length;

long chunks_number = FileSize / BUFFER_SIZE;

int difference =

(int)(FileSize - chunks_number * BUFFER_SIZE);

byte[] buffer =newbyte[BUFFER_SIZE];

for (int i = 0; i < chunks_number; i++)

{

instream.Read(buffer, 0, BUFFER_SIZE);

outstream.Write(buffer, 0, BUFFER_SIZE);

}

instream.Read(buffer, 0, difference);

outstream.Write(buffer, 0, difference);

outstream.Flush();

instream.Close();

}

Add a Response.Clear before you turn off buffering
Add a Response.End at the end of your method ( after instream.close )

the will insure no stray content was sent before or after the actual pdf content.


Thank you very much,mbanavige.

0 comments:

Post a Comment