Download file from Server using ASP.NET and C#.
Many times i have seen on dotnetspider, people ask questions about file downloading using ASP.NET and C#.
Here is small article that gives you clear idea of downloading file from server with User prompt for location to save file.
There are different ways to download file from server to client using Asp.Net and C#
Let's cook ?
Before cooking we need some preparation, we need to use Binary reader, Response object, MapPath
What is Binary reader
Binary reader reads data in primitive manner in binary format with encoding, convert whole file in binary format.
What is Response Object
This object gets the current HTTP response for current web request.
Following are some different methods that we can use for download file from server.
What is Server.MapPath
The File paths on local development machine are not the same as they are on your server, and from client machine you can not get the physical file path of exist on server.
for that we have to use Server.MapPath(//fileName); MapPath returns physical paths and file location.
string a = HttpContext.Current.Server.MapPath("~/App_Data/Example.xml");
output is physical path
here is code to download file from server (you should have a file exist on server)
string path = Server.MapPath("1.pdf"); //get physical file path from server
string name = Path.GetFileName(path); //get file name
string ext = Path.GetExtension(path); //get file extension
string type = "";
// set known types based on file extension
if (ext != null)
type = "text/HTML";
type = "text/plain";
type = "image/GIF";
type = "Application/pdf";
type = "Application/msword";
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
if (type != "")
Response.ContentType = type;
Response.End(); //give POP to user for file downlaod
here is output of above code
using above code you will get a POP up to save the file. Here we get content type of file and then append header to response object.
If you want to use the above code to support other file types, you must change the value in the ContentType string so that it points the appropriate file format.
The syntax of this string is usually formatted as "type/subtype,"
where "type" is the general content category and "subtype" is the specific content type.
For a full list of supported content types, refer to your Web browser documentation or the current HTTP specification
This code is compatible to Internet Explorer, Firefox, Opera, Chrome.
This is all about file download
Suggestion and Queries are most welcome
Thanks it was so usufull. :)