ASP.NET Web Pages - Files
This chapter introduces knowledge about working with text files.
Working with Text Files
In previous chapters, we have learned that web page data is stored in a database.
You can also store site data in text files.
Text files used to store data are often called flat files. Common text file formats are .txt, .xml, and .csv (comma-separated values).
In this chapter, you will learn:
- How to read and display data from a text file
Manually Adding a Text File
In the following example, you will need a text file.
On your website, if there is no App_Data folder, create one. In the App_Data folder, create a file named Persons.txt.
Add the following content to the file:
Persons.txt
Steven,Spielberg
Alfred,Hitchcock
Displaying Data from a Text File
The following example demonstrates 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>Reading Data from a File</h1>
@foreach (string dataLine in userData)
{
foreach (string dataItem in dataLine.Split(','))
{@dataItem <text> </text>}
<br />
}
</body>
</html>
Run example »
Example Explanation
UseServer.MapPathFind the exact path of the text file.
UseFile.ReadAllLinesOpen the text file and read all lines in the file into an array.
Each in the arraydata rowin thedata itemdata is displayed.
Displaying Data from an Excel File
Using Microsoft Excel, you can save a spreadsheet as a comma-separated text file (.csv file). At this point, each row in the spreadsheet is saved as a text line, and each data column is separated by commas.
You can use the example above to read an Excel .csv file (simply change the file name to the name of the corresponding Excel file).
Other Extensions