Easy Tutorial
❮ Prop Webcontrol Listcontrol Selecteditem Prop Webcontrol Tablerow Verticalalign ❯

ASP.NET Web Pages - Files


This chapter introduces knowledge about using text files.


Using Text Files

In previous chapters, we have learned that web data is stored in databases.

You can also store site data in text files.

Text files used to store data are commonly referred to as flat files. Common text file formats are .txt, .xml, and .csv (comma-separated values).

In this chapter, you will learn:


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. Inside the App_Data folder, create a file named Persons.txt.

Add the following content to the file:

Persons.txt


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>
@foreach (string dataLine in userData) {
    foreach (string dataItem in dataLine.Split(',')) {
        @dataItem <text>&nbsp;</text>
    }
}

Example Explanation

Use Server.MapPath to find the exact path of the text file.

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

Each data line in the array is displayed, with data items separated by commas.


Displaying Data from an Excel File

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

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

❮ Prop Webcontrol Listcontrol Selecteditem Prop Webcontrol Tablerow Verticalalign ❯