The following class adds a file DownloadResult
to your program:
public class DownloadResult : ActionResult
{
public DownloadResult()
{
}
public DownloadResult(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public string VirtualPath { get; set; }
public string FileDownloadName { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (!String.IsNullOrEmpty(FileDownloadName))
{
context.HttpContext.Response.AddHeader("content-disposition",
"attachment; filename=" + this.FileDownloadName);
}
string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
context.HttpContext.Response.TransmitFile(filePath);
}
}
To call it, do something like this in your controller method:
public ActionResult Download(string name)
{
return new DownloadResult
{ VirtualPath = "~/files/" + name, FileDownloadName = name };
}
Note the virtual path, which is a files directory in the root of the site; this can be changed to whatever folder you want. This is where you put your files for download.
http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx