473,385 Members | 1,753 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Corrupt PDF files When File is written to the response.

For my application, there users can upload and download files to the a
webserver. Straightforward enough. However, when they upload a PDF
file then try to download it, the file seems to be corrupted. The had
not been a problem before but it seems to have been introduced when I
refactored the writing to the response to a buffered version to prevent
potential OutOfMemoryExceptions (you wouldn't believe the size of some
of these files...).

Here's the code (pretty much jacked from a Microsoft knowledge base
article):

private void WriteToResponse(string filepath, string contentType,
NameValueCollection extraHeaders)
{
Stream iStream = null;

// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file name.
string filename = Path.GetFileName(filepath);

try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open,
FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;

Response.ContentType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Count; i++)
{
Trace.Write("adding Key value: " +
extraHeaders.GetKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHeader(extraHeaders.GetKey(i),
extraHeaders[i]);
}
}

// Read the bytes.
while (dataToRead 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch(IOException ioEx)
{
errorRow.Visible = true;
lblErrorMsg.Text = ioEx.Message;
log.Error(ioEx.ToString());
}
catch (Exception ex)
{
errorRow.Visible = true;
// Trap the error, if any.
log.Error(ex.ToString());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
}

Thanks in advance for any help.

Aug 22 '06 #1
7 10456
Trace not enabled ? All HTML stripped ? (using Response.Clear allows to make
sure you won't have a character coming from your APSX markup).

IMO The easiest path is to save the file (possibly using a content
disposition header) so that you can check the length. If not the length you
can do a file comparison to see where the file is corrupted.

--
Patrice

<ev*********@gmail.coma écrit dans le message de news:
11*********************@74g2000cwt.googlegroups.co m...
For my application, there users can upload and download files to the a
webserver. Straightforward enough. However, when they upload a PDF
file then try to download it, the file seems to be corrupted. The had
not been a problem before but it seems to have been introduced when I
refactored the writing to the response to a buffered version to prevent
potential OutOfMemoryExceptions (you wouldn't believe the size of some
of these files...).

Here's the code (pretty much jacked from a Microsoft knowledge base
article):

private void WriteToResponse(string filepath, string contentType,
NameValueCollection extraHeaders)
{
Stream iStream = null;

// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file name.
string filename = Path.GetFileName(filepath);

try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open,
FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;

Response.ContentType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Count; i++)
{
Trace.Write("adding Key value: " +
extraHeaders.GetKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHeader(extraHeaders.GetKey(i),
extraHeaders[i]);
}
}

// Read the bytes.
while (dataToRead 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch(IOException ioEx)
{
errorRow.Visible = true;
lblErrorMsg.Text = ioEx.Message;
log.Error(ioEx.ToString());
}
catch (Exception ex)
{
errorRow.Visible = true;
// Trap the error, if any.
log.Error(ex.ToString());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
}

Thanks in advance for any help.

Aug 22 '06 #2
Try using the (new in ASP.NET 2.0) Response.TransmitFile method.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"ev*********@gmail.com" wrote:
For my application, there users can upload and download files to the a
webserver. Straightforward enough. However, when they upload a PDF
file then try to download it, the file seems to be corrupted. The had
not been a problem before but it seems to have been introduced when I
refactored the writing to the response to a buffered version to prevent
potential OutOfMemoryExceptions (you wouldn't believe the size of some
of these files...).

Here's the code (pretty much jacked from a Microsoft knowledge base
article):

private void WriteToResponse(string filepath, string contentType,
NameValueCollection extraHeaders)
{
Stream iStream = null;

// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file name.
string filename = Path.GetFileName(filepath);

try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open,
FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;

Response.ContentType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Count; i++)
{
Trace.Write("adding Key value: " +
extraHeaders.GetKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHeader(extraHeaders.GetKey(i),
extraHeaders[i]);
}
}

// Read the bytes.
while (dataToRead 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch(IOException ioEx)
{
errorRow.Visible = true;
lblErrorMsg.Text = ioEx.Message;
log.Error(ioEx.ToString());
}
catch (Exception ex)
{
errorRow.Visible = true;
// Trap the error, if any.
log.Error(ex.ToString());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
}

Thanks in advance for any help.

Aug 22 '06 #3
hi,
did you try using Response.BufferOutput = true;
i thought that was supposed to buffer the output to the client in smaller
chunks.
..Net 2.0 has a method called Response.TransmitFile() which according to the
docs says that it sends a file straight to the client without loading the
contents into memory. it must do a direct stream transfer from the file to
the http response.

the thought of doing tracing in the middle of a binary write makes me a bit
suspicious, surely this would corrupt the download? not sure though if the
trace strings actually get written out with the response.

thanks
tim

<ev*********@gmail.comwrote in message
news:11*********************@74g2000cwt.googlegrou ps.com...
For my application, there users can upload and download files to the a
webserver. Straightforward enough. However, when they upload a PDF
file then try to download it, the file seems to be corrupted. The had
not been a problem before but it seems to have been introduced when I
refactored the writing to the response to a buffered version to prevent
potential OutOfMemoryExceptions (you wouldn't believe the size of some
of these files...).

Here's the code (pretty much jacked from a Microsoft knowledge base
article):

private void WriteToResponse(string filepath, string contentType,
NameValueCollection extraHeaders)
{
Stream iStream = null;

// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file name.
string filename = Path.GetFileName(filepath);

try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open,
FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;

Response.ContentType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Count; i++)
{
Trace.Write("adding Key value: " +
extraHeaders.GetKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHeader(extraHeaders.GetKey(i),
extraHeaders[i]);
}
}

// Read the bytes.
while (dataToRead 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch(IOException ioEx)
{
errorRow.Visible = true;
lblErrorMsg.Text = ioEx.Message;
log.Error(ioEx.ToString());
}
catch (Exception ex)
{
errorRow.Visible = true;
// Trap the error, if any.
log.Error(ex.ToString());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
}

Thanks in advance for any help.

Aug 22 '06 #4
Thanks for all your input. What it turned to be was my neglecting to
put in "Response.End()" at the end of this method. The files that were
being downloaded actually had the emitted HTML response appended to the
end of the file. It turns out that out of out of a whole cross section
of files, ranging form movie files to Office and images, the PDF was
most sensitive to this extra information after the EOF and was gettin
gcorrupted.
Tim_Mac wrote:
hi,
did you try using Response.BufferOutput = true;
i thought that was supposed to buffer the output to the client in smaller
chunks.
.Net 2.0 has a method called Response.TransmitFile() which according to the
docs says that it sends a file straight to the client without loading the
contents into memory. it must do a direct stream transfer from the file to
the http response.

the thought of doing tracing in the middle of a binary write makes me a bit
suspicious, surely this would corrupt the download? not sure though if the
trace strings actually get written out with the response.

thanks
tim

<ev*********@gmail.comwrote in message
news:11*********************@74g2000cwt.googlegrou ps.com...
For my application, there users can upload and download files to the a
webserver. Straightforward enough. However, when they upload a PDF
file then try to download it, the file seems to be corrupted. The had
not been a problem before but it seems to have been introduced when I
refactored the writing to the response to a buffered version to prevent
potential OutOfMemoryExceptions (you wouldn't believe the size of some
of these files...).

Here's the code (pretty much jacked from a Microsoft knowledge base
article):

private void WriteToResponse(string filepath, string contentType,
NameValueCollection extraHeaders)
{
Stream iStream = null;

// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file name.
string filename = Path.GetFileName(filepath);

try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open,
FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;

Response.ContentType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Count; i++)
{
Trace.Write("adding Key value: " +
extraHeaders.GetKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHeader(extraHeaders.GetKey(i),
extraHeaders[i]);
}
}

// Read the bytes.
while (dataToRead 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch(IOException ioEx)
{
errorRow.Visible = true;
lblErrorMsg.Text = ioEx.Message;
log.Error(ioEx.ToString());
}
catch (Exception ex)
{
errorRow.Visible = true;
// Trap the error, if any.
log.Error(ex.ToString());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
}

Thanks in advance for any help.
Aug 23 '06 #5
ev*********@gmail.com wrote:
Thanks for all your input. What it turned to be was my neglecting to
put in "Response.End()" at the end of this method. The files that were
being downloaded actually had the emitted HTML response appended to the
end of the file. It turns out that out of out of a whole cross section
of files, ranging form movie files to Office and images, the PDF was
most sensitive to this extra information after the EOF and was gettin
gcorrupted.

Glad you sorted it, but can I just ask, why do you continually
reallocate the buffer in your loop? Surely that would increase the
memory pressure?

Damien

Aug 23 '06 #6
hi,
you may prefer to use Response.Close()
in .net 1.1 i ran into ThreadAbortExceptions when using Response.End.
changing this to Response.Close() solved the problem.

tim
Aug 23 '06 #7
Oh thankyou thankyou thankyou

.... same problem!...

Aug 30 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Jole | last post by:
Hi I'm writing a program that needs to read from a file. In order for the program to be robust, it should somehow check that the file isn't corrupt, or stuffed in any way. For example, that...
4
by: Hal Vaughan | last post by:
I am writing out archive files using ZipOutputStream with the following code: aEntry is a global Array of ZipEntries llData is a LinkedList of the data corresponding to the the ZipEntry of the...
5
by: Vinay | last post by:
Hi I have a corrupt word file. I am able to open it with the code given below tr Dim pInfo As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo( pInfo.UseShellExecute...
4
by: SS | last post by:
We built an MSI file to deploy a .net app to the workstation. We created an HTML page that has a link to the MSI file. On a very sporadic basis, when the MSI is run we get the following message:...
8
by: Paw | last post by:
Greetings. I use asp. what I need is is when a visitor comes to the site, I need it to check the host name. if "www.hometowndigest.com" is the host, then check a folder named "something" and if...
8
by: ThunderMusic | last post by:
Hi, I'm currently building a little web site for me and my friends where we would like to be able to post big files (10Mb to 250Mb approx.) Right now the ASP.Net UploadFile control can't do it as...
0
by: Gustavo Ortega | last post by:
Hello, When I use the follwing aspx code to get a csv file via Internet Explorer in MS Excel, after comfirm dialog box as "Open content immediately" Excel displays a corrupt worksheet name as...
7
by: iporter | last post by:
I use the code below to authorise the download of certain files. Thus, instead of linking to the file in a wwwroot directory, I link to this code with the filename as a parameter, and the script...
4
by: GS | last post by:
How do I fix this corrupt resource file header problem? Corrupt .resources file. Got an unexpected EndOfStreamException while trying to read the ResourceReader header. When I open up properties,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.