Skip to main content

FileResult in MVC

We use FileResult when we want to return a file as a response to browser.Sometimes user may need to download specific files from application such as order details in pdf format or user guide for instructions.

Now we will see the code for downloading file using FileResult. FileResult is child class of ActionResult class. In our sample MVC application ,
we have stored a PDF file ‘UserGuide.pdf’ in Documents folder.

If you are not aware about how to create MVC application then please see my article First MVC Application, we will use the project created in that article.

Below is the code for downloading UserGuide from webapplication.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult Contact()
        {
            return View();
        }
       
        public ActionResult GetUserGuide()
        {
            string fileName = "~/Documents/UserGuide.pdf";
            return File(fileName, "application/pdf");
        }
    }
}

In above code “application/pdf” is content-type. We have to mention appropriate content-type for each file. Action method GetUserGuide() will provide an object of FileResult class using the below syntax:

return File(fileName, “application/pdf”);

FileResult class is child class of ContentResult so action method GetUserGuide() can return an object of FileResult class.

When you will write below URL in browser address bar and press enter key then file will be downloaded.

http://localhost:53204/Home/GetUserGuide

Here 53204 is port number which will be different on your machine.

Leave a Reply

Your email address will not be published. Required fields are marked *