ASP.NET Tutoria...login
ASP.NET Tutorial
author:php.cn  update time:2022-04-11 14:18:18

Web Pages files


ASP.NET Web Pages -Files


This chapter introduces you to working with text files.


Using text files

In the previous chapters, we have learned that web page data is stored in the 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 add a text file

In the example below, you will need a text file.

On your website, create an App_Data folder if you don't have one. In the App_Data folder, create a file called Persons.txt.

Add the following content to the file:

Persons.txt

George,Lucas
Steven,Spielberg
Alfred,Hitchcock


Display data in a text file

The following example demonstrates how to display data in 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»

Click the "Run Example" button to view the online example

Explanation of the example

UsageServer.MapPath Find the exact path to a text file.

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

The data for the data item in each data row in the array is displayed.


Displaying data from an Excel file

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

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


php.cn