Using code to dynamically push a download to the browser can come in handy in quite a few situations.
This simple function only takes a full file path...
private void PushFile(string fname)
{
FileInfo f = new FileInfo(fname);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + f.Name);
Response.AddHeader("Content-Length", f.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding","binary");
Response.ContentType = "application/octet-stream";
Response.WriteFile(f.FullName);
Response.End();
}
A good example of using this code would be this following snippet.
void Page_PreRender(Object ob, EventArgs ev)
{
string fname;
fname = Server.MapPath(Request.QueryString["filename"].ToString());
PushFile(fname);
}
That code simply takes a querystring value called "filename", which is a path relative to the site root, and pushes that to the browser using the PushFile function (shown above).
Of course it must be noted that the above two functions would be very unsafe because anyone could just change the querystring and download your web.config file, or global.asax. If youa re going to offer any sort of dynamic downloads, you've got to limit it to either authorized users, or to a specific folder for security.
Another possible use, is to protect images from being stolen. You can store your images outside of your web root folder, and only push them to authorized users for download.
Hope this helps someone.