Chapter 13 Exploring Text Files and String Processing 317
StreamReader can be important because if you try to read or write to the file again, you
might get an exception indicating that the process cannot access the file.
You can also use a combination of the My namespace and the StreamReader class.
The following example reads text from a file line by line and displays it in a text box.
The OpenTextFileReader method in the My namespace opens a StreamReader. The
EndOfStream property indicates the end of the file. The ReadLine method reads one line from
the file. When you are finished with a StreamReader, you should close it by calling the Close
method:
Dim AllText As String = "", LineOfText As String = ""
Dim StreamToDisplay As StreamReader
StreamToDisplay = My.Computer.FileSystem.OpenTextFileReader( _
"C:\vb10sbs\chap13\text browser\badbills.txt")
Do Until StreamToDisplay.EndOfStream 'read lines from file
LineOfText = StreamToDisplay.ReadLine()
'add each line to the AllText variable
AllText = AllText & LineOfText & vbCrLf
Loop
TextBox1.Text = AllText 'display file
StreamToDisplay.Close()
Tip Text files that are opened by using this syntax are called sequential files because you must
work with their contents in sequential order. In contrast, you can access the information in
a database file in any order. (You’ll learn more about databases in Chapter 18, “Getting Started
with ADO .NET .”)
Using the ReadAllText Method
The following exercise demonstrates how you can use an OpenFileDialog control and the
ReadAllText method to open a text file. The exercise also demonstrates how you can display
the contents of a text file in a text box. (For more information about using controls on the
Dialogs tab of the Toolbox to create standard dialog boxes, see Chapter 4, “Working with
Menus, Toolbars, and Dialog Boxes .”)
Run the Text Browser program
- Start Visual Studio, and open the Text Browser project in the
C:\Vb10sbs\Chap13\Text Browser folder.
The project opens in the Integrated Development Environment (IDE).