This article provides a sample showing how to download files from a directory in MVC 4.
Create a new ASP.NET MVC 4 Application as in the following:
Image 1
Image 2
Now, right-click on the Model Folder then select Add New Item -> Add a New Class.
Image 3
In DownLoadFileInformation use the following code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace FileDownloadInMVC4.Models
- {
- public class DownLoadFileInformation
- {
- public int FileId { get; set; }
- public string FileName { get; set; }
- public string FilePath { get; set; }
- }
- }

Image 4
In DownloadFiles.cs use the following code:
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.Hosting;
- namespace FileDownloadInMVC4.Models
- {
- public class DownloadFiles
- {
- public List<DownLoadFileInformation> GetFiles()
- {
- List<DownLoadFileInformation> lstFiles = new List<DownLoadFileInformation>();
- DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/MyFiles"));
- int i = 0;
- foreach (var item in dirInfo.GetFiles())
- {
- lstFiles.Add(new DownLoadFileInformation()
- {
- FileId = i + 1,
- FileName = item.Name,
- FilePath = dirInfo.FullName + @"\" + item.Name
- });
- i = i + 1;
- }
- return lstFiles;
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using FileDownloadInMVC4.Models;
- namespace FileDownloadInMVC4.Controllers
- {
- public class FileProcessController : Controller
- {
- //
- // GET: /FileProcess/
- DownloadFiles obj;
- public FileProcessController()
- {
- obj = new DownloadFiles();
- }
- public ActionResult Index()
- {
- var filesCollection = obj.GetFiles();
- return View(filesCollection);
- }
- public FileResult Download(string FileID)
- {
- int CurrentFileID = Convert.ToInt32(FileID);
- var filesCol = obj.GetFiles();
- string CurrentFileName = (from fls in filesCol
- where fls.FileId == CurrentFileID
- select fls.FilePath).First();
- string contentType = string.Empty;
- if (CurrentFileName.Contains(".pdf"))
- {
- contentType = "application/pdf";
- }
- else if (CurrentFileName.Contains(".docx"))
- {
- contentType = "application/docx";
- }
- return File(CurrentFileName, contentType, CurrentFileName);
- }
- }
- }

Image 6
Now run the application:

Image 7
Now click on any Download link.

Image 8

Shakir AliPosted Dec 19, 2017, 11:39 AM
Where is link for download ?
Riaz AdamPosted Apr 30, 2017, 12:01 AM
Hi how can i delete file/pdf from the folder
Bhuvan PandeyPosted Jun 13, 2016, 7:33 AM
How the download link will appear in view ?
Howard OiPosted Sep 21, 2015, 11:03 PM
how can i put password into the download file?
Arun BabuPosted Aug 30, 2015, 12:49 PM
how the download link appear in view ?