Download file: truncated [closed]
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
开发者_运维技巧Closed 7 years ago.
Improve this questionWe have an ASP.NET/C# 2.0 (.NET 2.0) web application.
To make the client to download a byte array programmatically we have a piece of code which looks like this:
Response.ContentType = contentType ?? "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Stream iStream = ...
byte[] buffer = new Byte[10000];
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;
}
}
Response.Flush();
Response.Close();
This works on all our installations but one (on IIS 6) where I got files truncated (about 30KB). Did you ever experience such a problem?
You haven't said where dataToRead
is coming from.
Personally I'd just read until length
returns a value <= 0, i.e. there's no more data to read.
byte[] buffer = new byte[8 * 1024];
while (true)
{
int length = input.Read(buffer, 0, buffer.Length);
if (length <= 0)
{
break; // There are alternative ways of expressing this
}
output.Write(buffer, 0, length);
}
I've only used Response.BinaryWrite
than going direct to the OutputStream in past without fault.
I would have resisted the buffer control flushes and closes, let the Response instance manage buffering, closure etc. too. And that loop seems a little unusual - I've usually read until no more bytes returned by the stream.
The problem was related to a module. We solved with Response.End()
to prevent the execution of the module.
精彩评论