Wednesday, January 28, 2009

Download Any File using ASP.NET

Very recently i have been shifted to ASP.NET programming. In the beginning i was facing a lots of problem. but now, I find myself bit comfortable with this.

i am providing a simple code for downloading any file from Web Server located in any directory on the Web Application folder.

make a reference to System.IO, and check that your web application has rights for Read/Write/Modify/Execute permission on the folder where you have placed all the files that you want your users to download.

FileStream fstream = new FileStream(Server.MapPath("FileToDownload"), FileMode.Open);
string file="";
file = "PrivacyPolicy.pdf";
byte[] bytBytes = new byte[fstream.Length];
fstream.Read(bytBytes, 0, (int)fstream.Length);
fstream.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + file);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(bytBytes);