| Answer: |
In a previous FAQ, FAQ: How can I read the entire contents of a text file into a string?, we saw how to read the entire contents of a text file into a string using the StreamReader class's ReadToEnd() method. To read the contents of a text file one line at a time use the ReadLine() method instead.
Note that the ReadLine() method returns either a string or a null (C#) or Nothing (VB.NET). If the ReadLine() method returns null or Nothing, it indicates that the end of the file has been reached. The string returned by the ReadLine() method does not contain the terminating carriage return.
An example of reading the contents of a file, one line at a time, and displaying them in a Web page appropriately (using <br>s to forcibly add line breaks):
' VB.NET Dim sr as New StreamReader("C:\SomeDir\SomeFile.txt")
Dim line as String = sr.ReadLine() Do While Not line is Nothing Response.Write(line & "<br>") line = sr.ReadLine() Loop
// C# StreamReader sr = new StreamReader(@"C:\SomeDir\SomeFile.txt");
string line = sr.ReadLine(); while (line != null) { Response.Write(line + "<br>"); line = sr.ReadLine(); }
|
The File class is located in the System.IO namespace, meaning that you will have to import this namespace into your ASP.NET Web page or code-behind class. If you are using a server-side script block in your ASP.NET Web page, add <%@ Import Namespace="System.IO" %> to the top of the ASP.NET Web page. If you are using a code-behind class, add the following:
' VB.NET Imports System.IO
// C# using System.IO;
|
Realize that you can easily translate a virtual path, like /files/SomeFile.aspx to its corresponding physical path, say C:\InetPub\wwwroot\files\SomeFile.aspx using the Server.MapPath() method. For more information on Server.MapPath() be sure to read Using Server.MapPath. |