Introduction
This article shows how to use a File result in a controller in MVC.
Step 1
Create a MVC project from the "Empty" template. Right-click on "Controllers" and select "Add" >> "Controller...".
Step 2
Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button.
Step 3
Name the controller as in the following:
And it will add an action result method to the controller.
Step 4
Now we need to create a view. Right-click on "Index" and select "Add View...".
Step 5
Name the view and select "Empty (without model)" as the template. Click on the "Add" button.
Step 6
Add a title to the index page.
Step 7
Create a folder "File" and save a Word document to test the FileResult sample.
Step 8
Filepathresult initializes a new instance of the filepathresult class by using the specified file name and content type.
Step 9
Create a link to call the downloadfile() method of the home controller.
Step 10
Run the project, click on "Download Word File" and it will download the Word file. You can find the file in the download folder.
Step 11
The file creates a filepathresult object using file name and content type. So create another action method and return the file.
Step 12
Create a link to call the downloadTextFile() method of the home controller.
Step 13
Run the project, click on "Return File" and the text file will be opened in the browser.