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.WriteFile(FilePath);
Response.End();
}
else
{
Response.Write("Error: Invalid parameters.");
}
%>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: