Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

ASP.NET Web Pages Files

ASP.NET Web Pages - Files


This chapter introduces knowledge about using text files.


Using Text Files

In previous chapters, we 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:


Manually add a text file

In the example below, 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

George,Lucas

Steven,Spielberg

Alfred,Hitchcock


Display Data from a Text File

The example below demonstrates how to display data from a text file:

Example

@{
var dataFile = Server.MapPath("~/App_Data/Persons.txt");
Array userData = File.ReadAllLines(dataFile);
}

Reading Data from a File

@foreach (string dataLine in userData)
{
foreach (string dataItem in dataLine.Split(','))
{@dataItem  }


}

Run Example »

Example Explanation

Use Server.MapPath Find the exact path of the text file.

Use File.ReadAllLines Open the text file and read all lines into an array.

Each in the arraydata rowThedata item's data is displayed.


Display Data from an Excel File

Using Microsoft Excel, you can save a spreadsheet as a comma-separated text file (.csv file). In this case, each row in the spreadsheet is saved as a text line, with each data column separated by a comma.

You can use the example above to read an Excel .csv file (just change the file name to the corresponding Excel file name).