Thursday, November 16, 2006

huge file transfer over http (asp.net way)

/*
Here is a method which reads the contents of the file in chunks and sends it to the client. this way we avoid unnecessary reading of the full file into the memory

Courtesy: Microsoft website
*/


public void DownloadFile(HttpResponse response, string filepath)
{
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 = "DownloadFileName";

// 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/octet-stream";
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();
}
}

/*
Other links related to this, may be useful for a reading.
http://www.odetocode.com/Articles/111.aspx
http://www.codecomments.com/archive290-2005-5-471328.html
http://www.ondotnet.com/pub/a/dotnet/2002/04/01/asp.html
http://www.yoda.arachsys.com/csharp/readbinary.html
http://msdn.microsoft.com/msdnmag/issues/05/11/BasicInstincts/
http://asp-net-whidbey.blogspot.com/
http://support.microsoft.com/kb/812406
http://www.eggheadcafe.com/articles/20011006.asp


*/

}

No comments: