Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a file? (Getting a server does not exist in context error)

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>
like image 425
sha Avatar asked Mar 27 '26 09:03

sha


1 Answers

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 == "") {
   .
   .
   .
}
like image 107
Niel Avatar answered Mar 29 '26 03:03

Niel