Home » Development » Allowing user to download a file in ASP.NET web page

Allowing user to download a file in ASP.NET web page

There are two ways to allow your end-users to download a file from your web site:

  1. Uploading the file to a FTP server then showing the link
  2. Starting the download in user’s browser without having user click on anything

The code below is used for the second one. It allows your user to download the file which is in a folder in your server (the machine on which IIS run)

Needless to say, it creates a file at first.

// Declarations of file name and path
FilePath = "C:\\sourcefolder\\";
FileName = "sourcefile.txt";

// Creating the file
System.IO.File.WriteAllText(FilePath + FileName, "test data");

// Downloading the file in user's browser
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.Flush();
response.End();

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment