I have an asp.net site that allows the user to upload quite large files - from 30 to 60 mb. Sometimes the download works fine, but often it fails at some other time before the download ends with a message that the connection to the server was reset.
Initially, I just used Server.TransmitFile, but after a little reading, I now use the code below. I also set the value of Server.ScriptTimeout to 3600 in the Page_Init event.
private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
if (ext != null)
{
switch (ext.ToLower())
{
case ".mp3":
type = "audio/mpeg";
break;
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name.Replace(" ", "_"));
}
if (type != "")
{
Response.ContentType = type;
}
else
{
Response.ContentType = "application/x-msdownload";
}
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
try
{
iStream = new System.IO.FileStream(path, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
iStream.Close();
}
Response.Close();
}
}
source
share