To download a file I am creating a function that checks a file's type and downloads the file from their location. After clicking on the download button a save dialog box is used for saving the downloaded file.
This is the function:
private void DownloadFile(string fname, bool forceDownload)
{
string Filepath = fname;
string Filename = Path.GetFileName(Filepath);
string ext = Path.GetExtension(Filepath);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".docx":
case ".rtf":
type = "Application/msword";
break;
case ".wav":
case ".Mp3":
type = "Application/media";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + Filename);
}
if (type != "")
Response.ContentType = type;
Response.WriteFile(Filepath);
Response.End();
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + Filename);
}
if (type != "")
Response.ContentType = Filetype;
Response.WriteFile(Filepath);
Response.End();
}
To force a download you have to pass true there.
Filepath is showing the path of the file from where we are downloading a file.

Priya JindalPosted Jun 28, 2016, 6:26 AM
I am not able to download..it only refreshes the page..
Satish VermaPosted Oct 13, 2014, 6:07 AM
Thanks,
Rowshan AliPosted Mar 6, 2013, 5:15 AM
Thanks . i am success by utilizing this code. best regurds to you. pray for me for gain.
Karthikeyan AnbarasanPosted Apr 6, 2011, 7:57 AM
can be explained a bit more!!!