473,624 Members | 2,439 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 OutOfMemoryExce ptions (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,
NameValueCollec tion 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.GetFileNam e(filepath);

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

Response.Conten tType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Co unt; i++)
{
Trace.Write("ad ding Key value: " +
extraHeaders.Ge tKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHea der(extraHeader s.GetKey(i),
extraHeaders[i]);
}
}

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

// Write the data to the current output stream.
Response.Output Stream.Write(bu ffer, 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(IOExcepti on ioEx)
{
errorRow.Visibl e = true;
lblErrorMsg.Tex t = ioEx.Message;
log.Error(ioEx. ToString());
}
catch (Exception ex)
{
errorRow.Visibl e = true;
// Trap the error, if any.
log.Error(ex.To String());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close() ;
}
}
}

Thanks in advance for any help.

Aug 22 '06 #1
7 10488
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*********@gm ail.coma écrit dans le message de news:
11************* ********@74g200 0c...legrou 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 OutOfMemoryExce ptions (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,
NameValueCollec tion 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.GetFileNam e(filepath);

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

Response.Conten tType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Co unt; i++)
{
Trace.Write("ad ding Key value: " +
extraHeaders.Ge tKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHea der(extraHeader s.GetKey(i),
extraHeaders[i]);
}
}

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

// Write the data to the current output stream.
Response.Output Stream.Write(bu ffer, 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(IOExcepti on ioEx)
{
errorRow.Visibl e = true;
lblErrorMsg.Tex t = ioEx.Message;
log.Error(ioEx. ToString());
}
catch (Exception ex)
{
errorRow.Visibl e = true;
// Trap the error, if any.
log.Error(ex.To String());
}
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.Transm itFile method.
Peter

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


"ev*********@gm ail.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 OutOfMemoryExce ptions (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,
NameValueCollec tion 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.GetFileNam e(filepath);

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

Response.Conten tType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Co unt; i++)
{
Trace.Write("ad ding Key value: " +
extraHeaders.Ge tKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHea der(extraHeader s.GetKey(i),
extraHeaders[i]);
}
}

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

// Write the data to the current output stream.
Response.Output Stream.Write(bu ffer, 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(IOExcepti on ioEx)
{
errorRow.Visibl e = true;
lblErrorMsg.Tex t = ioEx.Message;
log.Error(ioEx. ToString());
}
catch (Exception ex)
{
errorRow.Visibl e = true;
// Trap the error, if any.
log.Error(ex.To String());
}
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.Buffer Output = true;
i thought that was supposed to buffer the output to the client in smaller
chunks.
..Net 2.0 has a method called Response.Transm itFile() 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*********@gm ail.comwrote in message
news:11******** *************@7 4g2000cwt.googl egroups.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 OutOfMemoryExce ptions (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,
NameValueCollec tion 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.GetFileNam e(filepath);

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

Response.Conten tType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Co unt; i++)
{
Trace.Write("ad ding Key value: " +
extraHeaders.Ge tKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHea der(extraHeader s.GetKey(i),
extraHeaders[i]);
}
}

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

// Write the data to the current output stream.
Response.Output Stream.Write(bu ffer, 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(IOExcepti on ioEx)
{
errorRow.Visibl e = true;
lblErrorMsg.Tex t = ioEx.Message;
log.Error(ioEx. ToString());
}
catch (Exception ex)
{
errorRow.Visibl e = true;
// Trap the error, if any.
log.Error(ex.To String());
}
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.Buffer Output = true;
i thought that was supposed to buffer the output to the client in smaller
chunks.
.Net 2.0 has a method called Response.Transm itFile() 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*********@gm ail.comwrote in message
news:11******** *************@7 4g2000cwt.googl egroups.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 OutOfMemoryExce ptions (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,
NameValueCollec tion 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.GetFileNam e(filepath);

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

Response.Conten tType = contentType;
if(extraHeaders != null)
{
for (int i = 0; i < extraHeaders.Co unt; i++)
{
Trace.Write("ad ding Key value: " +
extraHeaders.Ge tKey(i)
+ ". Adding value: " +
extraHeaders[i]);
Response.AddHea der(extraHeader s.GetKey(i),
extraHeaders[i]);
}
}

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

// Write the data to the current output stream.
Response.Output Stream.Write(bu ffer, 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(IOExcepti on ioEx)
{
errorRow.Visibl e = true;
lblErrorMsg.Tex t = ioEx.Message;
log.Error(ioEx. ToString());
}
catch (Exception ex)
{
errorRow.Visibl e = true;
// Trap the error, if any.
log.Error(ex.To String());
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close() ;
}
}
}

Thanks in advance for any help.
Aug 23 '06 #5
ev*********@gma il.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 ThreadAbortExce ptions 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
12541
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 file may have been created but a crash occurred at that point in time (while it was being created), damaging the file. Now, my program which needs to read from this file, should first check that it's in good condition, and that it hasn't been...
4
19275
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 same index in aEntry public void save() { byte bBuffer = null; int i = 0;
5
3173
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 = Tru pInfo.FileName = "c:\corrupt.doc Dim p As Process = System.Diagnostics.Process.Start(pInfo Catch ex As Exceptio MsgBox(ex.ToString End Tr
4
11866
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: The cabinet file '_blahblahblah' required for this installation is corrupt and cannot be used. This could indicate a newtwork error, an error reading from the CD-ROM, or a problem with this package. The MSI file fails consistently on some...
8
2565
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 the folder does not exsist, create folder "www" and then copy folder "temp" and its contents. If the folder "www" is there, look in it, check to see if the files in folder "temp" are in there, if not, copy the files that are not from folder...
8
1717
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 we are limited 1) by the MaxRequestLength (4Mb) and 2) with big files (such as 250Mb) the server crashes because it only uses memory to cache the upload... Is there an easy way to develop an HTTP Module to handle the upload (links, tutorials,...
0
1825
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 given in: Response.Buffer = True Response.ClearContent()
7
9878
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 streams the file if the user is authorised. This has worked fine on PDFs, DOCs, XLS, etc. until today, and 18MB file presents the error message 'format error: not a pdf or corrupt'. Is there a file size limit, or a default that needs...
4
6736
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, resources, they looked ok to me. I even click on each item and they open up in pain just fine. what can I do?
0
8240
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8175
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8680
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8482
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6111
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2610
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.