Now add a controller and add an IActionResult HttpGet method. In this method we will add a controller and add the below code in the View.
@{
ViewData["Title"] = "Home Page";
}
<h1>File Data In wwwroot Folder</h1><br />
<span>@ViewBag.FileData</span>
[HttpGet]
public IActionResult Index()
{
string folderPath = @"\wwwroot\DemoFiles\";
string filename = "DemoTextFile.txt";
string finalPath = string.Format("{0}{1}{2}",Directory.GetCurrentDirectory(), folderPath, filename);
if (Path.Exists(finalPath))
{
var textFileData = System.IO.File.ReadAllText(finalPath);
ViewBag.FileData = textFileData;
}
else
{
ViewBag.Message = "Given file does not exists.";
}
return View();
}
string finalPath = string.Format("{0}{1}{2}",
Directory.GetCurrentDirectory(), folderPath, filename);
var textFileData = System.IO.File.ReadAllText(finalPath);
ViewBag.FileData = textFileData;
In above code I have used System.IO.File.ReadAllText(finalPath) to rea the file content. Here if we dont user System.IO we will get the error. So, it always use it as given in the code.
Error!
ControllerBase.File(byte[], string)' is a method, which is not valid in the given context
After reading the date i have stored into ViewBag. This we will display in view. Now let's put a break point and check the output.
In above code we are able to get the text file content. Now let's press F5 to check the output.