Thursday, July 31, 2008

Implementing a File Download in ASP.NET

Recently I gave some help to a colleague of mine implementing a file download. So I thought of sharing it with you.
If you need to make a web site user to download a file from your site you have to use HTTPResponse.Page.Response object. By using this you will be able to make the user download numerous kinds of files to their machines. The code required is as follows.

// This defines the type of the file that you are allowing to download.
Response.ContentType = "application/vnd.ms-excel";
// Path to the file to be downloaded.
string FilePath = MapPath("Xcel.xlsx");
// Initiating the file download.
Response.WriteFile(FilePath);
Response.End();

The above code will let the user download an Excel file named Xcel. Aprt from Excel you can use other file types as well by changin the Response.ContentType to the required file type.
A list of available content types are as follows.

No comments: