HOW TO DOWNLOAD FILE USING ASP.NET
Here we discuss how to write code in ASP.NET by executing which we can download any specified file. Many developers require such type of code in their application of ASP.NET but they do not know how to write such a code in ASP.NET, which provides such type of functionality of downloading of file from any specified location using ASP.NET.
In this article I am going to discuss on same matter. Downloading file by executing one file is so easy but such type of code we is difficult to find when we are trying to find it out in search engines like Google, AltaVista and many more so as a part of solution I have provided one code example which is used to download any specified file from any specified location which is coded in ASP.NET. You just go through this example to clearly understand all the programmatic aspects.
Now here you have to keep in mind that there is no special classes are available to do such type of functionality of downloading file but by indirect way we have to complete the task of downloading file from any specified location. In your development stage, you might have performed many operations using file handling like creating new file, copying file from one location to other location, deleting file and opening file, etc. If you are aware of file handling operation then you may know that before opening file we have to specify whether we want to write in file or we want to read from file. As per your choice you can perform operation. Now suppose you want to open one file which is already created at that time you are writing code for that and if you have clearly observed the code then you might have came to know that before opening file it will ask you whether you want to open file directly or you want to save file in your computer and then you want to open it. So now, you might have got a slight idea that I have provided you solution how to write code for download file from specified location. Now let me end the suspense and let me provide you the code for downloading file using ASP.NET.
‘first of all open file using FileStream Class
Dim fst As New FileStream(Server.MapPath("abc.txt"), FileMode.Open)
‘create string variable to store filename
Dim fl As String
‘store the file name to string variable
fl = "abc.txt"
‘store the total number of byte to read
Dim bytBytes(fst.Length) As Byte
‘read file byte by byte
fst.Read(bytBytes, 0, fst.Length)
‘close the file after reading it
‘add the header to the file which is file name
Response.AddHeader("Content-disposition", "attachment; filename=" & fl)
‘specify the content type
Response.ContentType = "application/octet-stream"
‘write all the byte to newly created file