C# Force file download

To force a file to download, instead of being opened by the browser create a page called (something like) force.aspx and populate it with the C# code below. Then in the page containing the link that you want to force as a download use: <a href=”force.aspx?f=filename.ext”>Download</a> as the link, replacing filename.ext with the relevant filename.

The Code:

<%@ Page Language="C#" %><%
String File = "";
if (Request.Params.Get("f") != null) File = Convert.ToString(Request.Params.Get("f"));
if (File != "")
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename=" + File);
string FilePath = MapPath(File);
Response.Write("Error: Invalid parameters.");