Pages

Thursday, December 12, 2013

Read from a text file using the FileStream StreamReader class (ASP.NET)

If you're writing to text files in .NET, chances are there will come a time when you want to read from those text files as well. To accomplish this task, you'll need to use the StreamReader class. The StreamReader class is a member of the FileStream class, which provides all the functionality you need to read and write data to text files.


The following codë reads one line from a text file:

Dim fs As System.IO.FileStream
Dim sr As System.IO.StreamReader
fs = New System.IO.FileStream("c:\txtfile.txt", System.IO.FileMode.Open)
sr = New System.IO.StreamReader(fs)

Response.Write(sr.ReadLine & "<br>")
sr.Close()


To read all the lines in a text file, use ReadLine to obtain the first line, then place a second call to ReadLine inside a loop. Read until the method returns an empty string, like so:

Dim st As String
Do
  st = sr.ReadLine
  Response.Write(st & "<br>")
Loop Until st = ""


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.