Search 
DailyCoding > Web

How to force a file to download in ASP.NET

This article is about how we can force the user to dowload a particlar file or file type by adding the content-disposition header
Author admin on Jun 16, 2008 2 Comments
Rate it    (Rated 3 by 2 people)
284 Views

There are lots of file type which can be handled by IE (or other browsers Firefox, Opera etc.) like html, xml, jpeg, gif, swf, pdf, doc etc. In case the browser can not handle the a particular file type it will ask you to open or save that file. Sometime you may want to force the user to download a particular file even though browser can open that file type because of any of your business need. This can be easily achieved by adding the content-disposition header in the response of your page.

Take below example. Here we are writing a gif file in response and forcing the user to download this file.

protected void Page_Load(object sender, EventArgs e)
{
  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=logo_large.gif");
  
  Response.ContentType = "image/GIF";
  Response.WriteFile(Server.MapPath(@"~/logo_large.gif"));
  
  Response.End();
}

If you see above code then you can notice we can also specify the file name. This technique will work for other file types too.

ASP.NET | Web

Discussion

Mark Laycock On Jul 27, 2008 02:51 AM
Interesting but it doesn't indicate where the code should be inserted (between which tags, etc) - as a newbie I'm trying to get people to download PDF files from web pages (but not open in the browser) but not having any success in coding this.

Daily Coder On Jul 27, 2008 11:04 PM
Mark, The code needs to be placed in the code behind ".cs" of the page and there should be no tags in the ".aspx" page except the @Page attribute on the top. Let me know in case you face any problem.

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved