Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 13 Exploring Text Files and String Processing 315


The My namespace is truly a “speed dial” feature, fully explorable via the Microsoft
IntelliSense feature of the Code Editor. For example, to use a message box to display the
name of the current computer followed by the name of the current user in a program, you
can simply type:

MsgBox(My.User.Name)

This produces output similar to the following:

The My.Computer object can display many categories of information about your computer
and its files. For example, the following statement displays the current system time (the local
date and time) maintained by the computer:

MsgBox(My.Computer.Clock.LocalTime)

This produces output like this (your date and time will probably be different):

You can use the My.Computer.FileSystem object along with the ReadAllText method to open
a text file and display its contents within a text box object. Here’s the syntax you can use
if you have a text box object on your form named txtNote (as in the last sample program)
and you plan to use an open file dialog object named OpenFileDialog1 to get the name
of the text file from the user:

Dim AllText As String = ""
OpenFileDialog1.Filter = "Text files (*.txt)|*.txt"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then 'display Open dialog box
AllText = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
txtNote.Text = AllText 'display file
End If

The ReadAllText method copies the entire contents of the specified text file to a string
variable or object (in this case, a string variable named AllText), so in terms of performance
and coding time, ReadAllText is faster than reading the file one line at a time.
Free download pdf