Streamed Downloading Of Files
-
Hi Everyone.... I would be very grateful if anyone could help with a problem I am having to do with file downloading from ASP.NET. I am absolutely stuck and this is driving me mad. I have written an HttpHandler that is used to download files. In the ProcessRequest function, I open a file, and then in a while loop stream the file to the HttpResponse ouput stream. I continue until the whole file is streamed to the client or the HttpResponse method IsClientConnected returns false. If a big file is downloaded and the user chooses Open in the resulting IE File Download box, everything is OK - If the user hits cancel during the download, IsClientConnected goes false and the code exits. However, if the user chooses Save in the IE File Download box and then cancels half way through, IsClientConnected does not go false - it remains true and the aspnet process locks up, meaning that subsequent page requests fail. I have Googled and I can see many other people have had this problem, but I just haven't got a clue how to fix it. Pleeeeeease can anyone help!? This is driving me nuts. Thanks! The code in ProcessRequest looks something like this....
System.Web.HttpResponse httpResponse = context.Response;
httpResponse.ContentType = "application/octet-stream";
httpResponse.AddHeader("Content-Disposition", "attachment; filename=\"image1.bmp\"");System.IO.Stream stream = new System.IO.FileStream(
@"C:\Home\downloads\image1.bmp", System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);long bytesToRead = stream.Length;
httpResponse.AddHeader("Content-Length", bytesToRead.ToString());
while (bytesToRead > 0)
{
if (httpResponse.IsClientConnected)
{
// Just so we get opportunity to hit cancel button on download screen
System.Threading.Thread.Sleep(1);// Read the data into the buffer and write into the output stream long toRead = Math.Min(8192, bytesToRead); byte\[\] buffer = new Byte\[toRead\]; int length = stream.Read(buffer, 0, (int)toRead); httpResponse.OutputStream.Write(buffer, 0, length); httpResponse.Flush(); // Continue reading remaining bytes bytesToRead = bytesToRead - length; } else { // We might get here if the user hit cancel on their download file popup window bytesToRead = -1; }
}
finally
{
stream.Close();
httpResponse.End();
}