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; }
- }
- }
Now, again right-click on Mode then select Add New Item -> Add New Class.
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;
- }
- }
- }
Now open FileProcessController and do the following code:
- 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
- {
-
-
-
- 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);
- }
- }
- }
Now right-click on the Index Action then select Add A View.
Image 6
Now run the application:
Image 7
Now click on any Download link.
Image 8