ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods

Force Download any file!

Forces your browser to download any kind of file instead of trying to open it inside the browser (e.g. pictures, pdf, mp3). Works in Chrome, Opera, Firefox and IE 7 & 8!

Source

using System;
using System.Web;
using System.Web.UI;

public static class ResponseHelper
{
	public static void ForceDownload(this HttpResponse Response, string fullPathToFile, string outputFileName)
	{
		Response.Clear();
		Response.AddHeader("content-disposition", "attachment; filename=" + outputFileName);
		Response.WriteFile(fullPathToFile);
		Response.ContentType = "";
		Response.End();
	}
}

Example

// full path to your file
var yourFilePath = HttpContext.Current.Request.PhysicalApplicationPath + "Files\yourFile.jpg";
// save downloaded file as (name)
var saveFileAs = "yourFile.jpg";

// start force download of your file
Response.ForceDownload(yourFilePath, saveFileAs);

Author: Mikhail Tsennykh

Submitted on: 14 okt 2010

Language: C#

Type: System.Response

Views: 13755