ASP.NET: Download Files From A Website

Here's a simple trick to prevent direct linking to your downloads, or to return binary files that are dynamically created within an ASP.NET website. Here's some example code on how to download a PDF:

DateTime time = DateTime.Now; 
String filename = time.ToString("yyyyMMddhhmmss") + ".pdf"; 
Response.ContentType = "application/pdf"; 
Response.AddHeader("content-disposition", "attachment; filename=" + filename); 
Response.BinaryWrite(binaryFile);

The important part to adapt here is Response.ContentType = "application/pdf";. You need to go to IANA.org to find the correct MIME encoding for the particular file that you want to send.  Just hook this up to a LinkButton or similar event, and users will be able to dynamically download content from your site.  I'm implementing this particular part in a project I am doing for dynamically creating PDFs with an open source PDF generator called PDFsharp.

Posted on Apr 15
Written by Wayne Hartman