So for the last few week's I've been working on my document management system, for some reason clients were having issues download files over 5 meg in size. I was using the following code for file downloads:
Response.ContentType = "application/pdf";
Response.WriteFile(filePath);
Response.AddHeader("Content-Disposition", "inline;filename=" + fileName");
This was causing an exception in w3wp.exe each time a file was downloaded and an inflated file size. I couldn't really find a proper explanation on why its happening, my first thought was that it was taking too long for the file to be sent from memory to the worker process hence timing out and crashing w3wp.exe... Either way I have found a solution here:
System.IO.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 to download including its path.
string filepath = "filePath";
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "attachment; filename="fileName");
// 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 (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}Response.Close();}
Cool, well I hope that helps someone out there!
blog comments powered by Disqus
