Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

316 Part II Programming Fundamentals


Because of this speed factor, the My namespace provides an excellent shortcut to many
common programming tasks. It is important to take note of this feature and its possible uses,
but the My namespace is efficient here because we are reading the entire text file.

If you forget the syntax for the ReadAllText method, you can quickly insert an example by
using the Insert Snippet command. As described in Chapter 7, “Using Loops and Timers,“
the Insert Snippet command allows you to insert common code snippets in the Code
Editor. To insert the ReadAllText method, display the Code Editor, and on the Edit menu,
click IntelliSense, and then click Insert Snippet. In the Insert Snippet list box, double-click
Fundamentals – Collections, Data Types, File System, Math; double-click File System –
Processing Drives, Folders, And Files; and then double-click Read Text From A File. This
inserts the following code snippet:

Dim fileContents1 As String
fileContents1 = My.Computer.FileSystem.ReadAllText("C:\Test.txt")

The StreamReader Class


The StreamReader class in the .NET Framework library allows you to open and display text
files in your programs. I’ll use this technique several times in this book when I work with text
files (for example, in Chapter 16, “Inheriting Forms and Creating Base Classes”). To make it
easier to use the StreamReader class, you add the following Imports statement to the top
of your code, as discussed in Chapter 5, “Visual Basic Variables and Formulas, and the .NET
Framework”:

Imports System.IO

Then, if your program contains a text box object, you can display a text file inside the text
box by using the following program code. (The text file opened in this example is Badbills .txt,
and the code assumes that an object named TextBox1 has been created on your form .)

Dim StreamToDisplay As StreamReader
StreamToDisplay = New StreamReader("C:\vb10sbs\chap13\text browser\badbills.txt")
TextBox1.Text = StreamToDisplay.ReadToEnd
StreamToDisplay.Close()

In this StreamReader example, I declare a variable named StreamToDisplay of the type
StreamReader to hold the contents of the text file, and then I specify a valid path for the file
I want to open. Next, I read the contents of the text file into the StreamToDisplay variable
by using the ReadToEnd method, which retrieves all the text in the file from the current
location (the beginning of the text file) to the end of the text file and assigns it to the Text
property of the text box object. The final statement closes the StreamReader. Closing the
Free download pdf