ASP.NET Web Pages - Files

This chapter explains the processing of text files.

Processing text files

In the previous chapter, we learned about web data stored in databases.

Your website may store data in text files.

Text files that store data are usually called flat files. Common text file formats are .txt, .xml, and .csv (comma-delimited values).

In this chapter, you will learn:

  • How to read and display data from a text file

Manually add a text file

In the following examples, you will need a text file.

If there is no App_Data folder on your website, create one. In the App_Data folder, create a new file named Persons.txt.

Add the following content to this file:

Persons.txt

Bill,Gates
Steve,Jobs
Mark,Zuckerberg

Display Data from Text File

The following example shows how to display data from a text file:

Example

@{
var dataFile = Server.MapPath("~/App_Data/Persons.txt");
Array userData = File.ReadAllLines(dataFile);
}
<!DOCTYPE html>
<html>
<body>
<h1>Read Data from File</h1>
@foreach (string dataLine in userData) 
{
  foreach (string dataItem in dataLine.Split(',')) 
  {@dataItem <text> </text>}
  <br />
}
</body>
</html>

Run Instance

Example Explanation

Server.MapPath Find the exact text file path.

File.ReadAllLines Open this file and then read all the text lines in the file into an array.

display eachData RoweachData Item.

Display data in Excel files

With Microsoft Excel, you can save an electronic spreadsheet as a comma-separated text file (.csv file). When you do this, each row in the spreadsheet is saved as a text line, and each data column is separated by a comma.

You can use the examples above to read an Excel .csv file (change the filename to the name of the Excel file).