How to read from a file in ASP.NET

Data may be stored in files on the disk, and it is common for programs to extract information via file reading.

ASP supports file reading as well.

Syntax

The first step before reading data from any file is to specify its directory. The file path is sent as input to the Server.MapPath function, which returns the physical path to the root of that file.

var fileContents = Server.MapPath("~/file.txt");;

Subsequently, data contents are fetched from the file by sending the physical path as input to the File.ReadAllLines function and storing it in an array.

Array dataContents = File.ReadAllLines(fileContents);

Each line stored as a string in the array above can be accessed, formatted, and printed using a for loop.

Example

The program below reads data from a file named file.txt, which contains some fruits and vegetables and is present in the same directory as our ASP program.

To format the data before printing, we use two for loops. The first loop fetches each string that was read from the file, and the second loop splits each data element of the string with , as the delimiter.

Data is printed onto the screen using the text element.

index.html
file.txt
@{
var fileContents = Server.MapPath("~/file.txt");
Array dataContents = File.ReadAllLines(fileContents);
}
<!DOCTYPE html>
<html>
<body>
<h2>This program reads data from a given file!</h2>
@foreach (string contentLine in dataContents)
{
foreach (string dataElement in contentLine.Split(','))
{@dataElement <text>&nbsp;</text>}
<br />
}
</body>
</html>

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved