Please check the above wwwroot folder, in this folder I have added 3 files. We are going to read all the files in asp.net core mvc application and display it on view. Now to perform the action first we will add a controller class file in this class code file ass a [httpGet] IActionResult.
[HttpGet]
public IActionResult Index()
{
return View();
}
Now let's create a new model class file and add the below code in it. In this model class file, we will define a property of List<string> type and in this property, we will store all the file name.namespace Project.Models
{
public class FileListModel
{
public List<string> FileNameList { get; set; }
}
}
After creating the model class file, we add code to read the file from folder in [HttpGet] method.
[HttpGet]
public IActionResult Index()
{
string parentPath = @"\wwwroot\DemoFiles\";
string finalPath = string.Format("{0}{1}",Directory.GetCurrentDirectory(), parentPath);
FileListModel fileListModel = new FileListModel();
if (Path.Exists(finalPath))
{
fileListModel.FileNameList = new List<string>();
var data=Directory.GetFiles(finalPath);
foreach(var item in data)
{
fileListModel.FileNameList.Add(Path.GetFileName(item));
}
}
else
{
ViewBag.Message = "Given path does not exists.";
}
return View(fileListModel);
}
In above method I have taken two variables first for folder path and second for storing the final folder path from where we will read all the files. I have used string.Foramt to concatenate path the folder path. Now we will create object for the model class named as FileListModel. string parentPath = @"\wwwroot\CustomFolder\";
string finalPath = string.Format("{0}{1}", Directory.GetCurrentDirectory(), parentPath);
FileListModel fileListModel = new FileListModel();
After getting the path and model class object, we will validate the folder path exists or not by using Path.Exists(finalPath). If path exists, we will read the file by using Directory.GetFiles(finalPath). After getting all the files we will store it in model list.
While storing into the list is we want to use the complete path we will simply store the value otherwise we will use Path.GetFileName(--) to get only the file name by passing the collected file path.
var data=Directory.GetFiles(finalPath);
foreach(var item in data)
{
fileListModel.FileNameList.Add(Path.GetFileName(item));
}
We create a view in the asp.net core mvc application with default layout. Here we will place out code to read and display the file list from the folder.
@model FileListModel
@{
ViewData["Title"] = "Home Page";
}
<h1>File List From wwwroot</h1>
<br />
<span style="color:red;font-weight:bold;"> @ViewBag.Message</span>
<br />
@foreach (var file in Model.FileNameList)
{
<div>@file</div>
}
In above code I have inherited the model class and user FileNameList to populate the collected file name. By using foreacch look I have displayed the file name. Now let's check final output.