I found this code on the documentation and it is giving me server doesn't exist in context error(for Server.MapPath()). Is there any other way of reading a file? I tried entering the absolute path of the file I want to read, but it gives null pointer exception. thanks P.S I am using .net core 3.1
@{
var result = "";
Array userData = null;
char[] delimiterChar = {','};
var dataFile = Server.MapPath("~/App_Data/data.txt");
if (File.Exists(dataFile)) {
userData = File.ReadAllLines(dataFile);
if (userData == null) {
// Empty file.
result = "The file is empty.";
}
}
else {
// File does not exist.
result = "The file does not exist.";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Reading Data from a File</title>
</head>
<body>
<div>
<h1>Reading Data from a File</h1>
@result
@if (result == "") {
<ol>
@foreach (string dataLine in userData) {
<li>
User
<ul>
@foreach (string dataItem in dataLine.Split(delimiterChar)) {
<li>@dataItem</li >
}
</ul>
</li>
}
</ol>
}
</div>
</body>
</html>
If you are using MVC project, Why not read the file in Controller, and pass that text via Model? something like below?
public IActionResult Index()
{
var result = "";
Array userData = null;
char[] delimiterChar = { ',' };
var dataFile = Server.MapPath("~/App_Data/data.txt");
if (File.Exists(dataFile))
{
userData = File.ReadAllLines(dataFile);
if (userData == null)
{
// Empty file.
result = "The file is empty.";
}
}
else
{
// File does not exist.
result = "The file does not exist.";
}
return View(result);
}
and then on Index.cshtml
@model string
@if (@Model == "") {
.
.
.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With