Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 13 Exploring Text Files and String Processing 345


in your study of Visual Basic programming skills and in your use of the Visual Studio IDE. Take
a short break, and I’ll see you again in Part III, “Designing the User Interface”!

Chapter 13 Quick Reference


To Do This
Display an Open
dialog box

Add an OpenFileDialog control to your form, and then use the ShowDialog
method of the open file dialog object. For example:
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Read a text file
by using the My
namespace

Use the My.Computer.FileSystem object and the ReadAllText method.
For example (assuming that you are also using an open file dialog object
named ofd and a text box object named txtNote):
Dim AllText As String = ""
ofd.Filter = "Text files (*.txt)|*.txt"
If ofd.ShowDialog() = DialogResult.OK Then
AllText = _
My.Computer.FileSystem.ReadAllText(ofd.FileName)
txtNote.Text = AllText 'display file
End If
Read a text file
by using the
StreamReader class

Add the statement Imports System.IO to your form’s declaration section,
and then use StreamReader. Use the ReadToEnd method to read the entire
file. When finished, call the Close method. For example, to display the file in
a text box object named TextBox1:
Dim StreamToDisplay As StreamReader
StreamToDisplay = New StreamReader( _
"c:\vb10sbs\chap13\text browser\badbills.txt")
TextBox1.Text = StreamToDisplay.ReadToEnd
StreamToDisplay.Close()
Read a text file line
by line

Use StreamReader and the ReadLine method. Use the OpenTextFileReader
method in the My namespace to open a StreamReader. To check for the
end of the file, use the EndOfStream property:
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()
AllText = AllText & LineOfText & vbCrLf
Loop
TextBox1.Text = AllText 'display file
StreamToDisplay.Close()
Display a Save As
dialog box

Add a SaveFileDialog control to your form, and then use the ShowDialog
method of the save file dialog object. For example:
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
Free download pdf