How to Serve Files to User in Asp.Net MVC

Let the user download a file from server is not a typical task, programmer have to write some lines of code which will execute the task. Asp.Net MVC action with returning type FileResult will complete this task in few task listed in the article.

After uploading file/files on the server, how to deliver/serve a file for user to download and save on an individual system depends on the way of storing the file on the server by programmer. Programmer can provide a simple link to an action including some lines of code to perform the task.

In the controller write below line of c# code in the action named “DownloadFile” which will access the file saved on the root of this project and then prompt user to Open/Save that file.

public FileResult DownloadFile()
var file = Server.MapPath("~/download file.txt");
return File(file, "Text", "download file");

These two line of code will sufficient to prompt the user, now in view page create an actionline which will redirect the user to this action. The second line of code will creates a System.Web.Mvc.FilePathResult object by using the file name, the content type, and the file download name.

@Html.ActionLink("Download File", "DownloadFile");

Run the project and particular controller/action then click on the link created above. This will show an opening download file window having two option to open or save that file, as shown in the below image:

How to Serve Files to User in Asp.Net MVC

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google