Tuesday, June 27, 2006

Downloading Files

The following block of code allows you to download files automatically to the user desktop

//Open the file
FileStream fs = File.Open(@"C:\filename.txt", FileMode.Open);
//Create a btye array
byte[] bytBytes = new byte[fs.Length];
try
{
//find the length of the file and read the file
string longint = fs.Length.ToString();
int temp = int.Parse(longint);
fs.Read(bytBytes, 0, temp);
fs.Close();

//Parse the file so that it will be download to user's desktop
Response.AddHeader("Content-disposition", "attachment; filename=C:\filename.txt")
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(bytBytes);
Response.End();
}
catch (Exception er)
{
//In event of error
fs.Close();
Console.WriteLine(er.Message);
}


No comments:

Post a Comment