Wyo VB Lecture Notes
Objective #1 - Write data to a text file.
- Until this point in this course, you have not been able to permanently store data from one execution of a program to another separate execution. Variables can be used to store data of course but once the program ends this data is wiped out. For example, to store a high score of a game or to store names, addresses and phone numbers into an address book are two situations in which you would store data to a text file.
- The text file where you need to store date is not part of the VB program. It is a file that could be viewed like most others on the computer using a program such as Microsoft Word. We will use the program Notepad however to create, view, and edit text files. While many file extension could be used for text files, we will use the common file extension .txt.
- Sometimes, It is best to first create a file that
you want to use to store data with the program Notepad. Type some dummy data into the file. For example, if we are going to use a file named highscore.txt to store the high score to a VB
game, we would logically type a zero into the file.
- To write or read data to or from a file using StreamWriter or StreamReader as described below, you
must add the line of code
Imports System.IO
to the very top of your program above the line of code Public Class Form1.
- In order to overwrite the zero that is stored in highscore.txt, you must first declare a StreamWriter variable with the declaration
statement
Dim outputFile As StreamWriter
Then you must create
the
connection
between
the
StreamWriter variable
and
the
file itself. That is why this kind of variable is also known as a file
pointer. To create this connection, you must "open" the file with a statement
like this:
outputFile = File.CreateText("highscores.txt")
where the file pointer outputFile now points ("is connected to") the actual file
on
the
hard
drive
named
highscores.txt.
However the two lines of code above
could be consolidated to this single statement
Dim outputFile As StreamWriter = File.CreateText("highscores.txt")
- If you want to store this file in another folder other than the folder with your exe file, you can use the following syntax. For example, to store the file in a folder
named "files" that is one level up from the folder with your exe file, you can use
outputFile = File.CreateText(Application.StartupPath + "..\files\highscores.txt")
- Opening a file in this manner does not open the file on the computer screen. Instead, an open connection is established behind the scenes.
- When a text file is opened the file pointer points to
the beginning of the first line of data in that file. The WriteLine method
is used in the following statement to write the value stored
in the variable mintScore onto
the first line of the file highscores.txt
outputFile.WriteLine(mintScore)
- It's good style to properly close
the connection between a StreamWriter and the
file
that
it
is connected
to
when
you are
finished
using it. This is done with the Close method like this
outputFile.Close()
If you don't close a text file when it's finished being used you risk
the danger of corrupting the file and losing any data stored there.
- When you connect a StreamWriter to a text file, it assumes
that you want to overwrite the data that is stored there. By default, it
will not automatically append data to the end of the existing file. Usually,
it is wise to first open the file with a StreamReader (explained below) to
read the original data from the file into variables in your VB program, then
close the StreamReader and open the file with a StreamWriter. Unfortunately,
a text file can only be opened in either the write mode or the read mode.
That is, you cannot read and write at the same time to the same file. There
is an append mode that can be used with a StreamWriter that can be used to
append data to the end of an existing text file. We will not be studying
the append mode in this course however.
Objective #2 - Read data from a text file.
- The data in an existing text file can be stored in variables in your program by reading the file. It doesn't matter whether the text file was created with the program Notepad or it was a file created using a StreamWriter.
- A text file used with StreamReader or StreamWriter is often called a sequential
access file. Each line of data is called a record and the records are therefore stored sequentially. It is similar to a video cassette tape. You can only read the fourth line of data until after you've read the first three lines of data. You cannot jump ahead and read a random line of data. Furthermore, with a sequential access file, you cannot move backwards very easily. Once you've read a given line of data, the cursor automatically advances to the beginning of the next line of data.
- To read data from a text file, you must first declare
a variable as a StreamReader with a statement like this
Dim inputFile As StreamReader
Then you must create the connection between the StreamReader variable and the file itself with a statement like
inputFile = File.OpenText("highscores.txt")
or
inputFile = File.OpenText(Application.StartupPath + "..\files\highscores.txt")
These two statements could be combined into one line of code like this
Dim inputFile As StreamReader = File.OpenText("highscores.txt")
Then the following statement would be used to "read" the first line of data
in the text file and store that value into the variable intHighScore
intHighScore = Val(inputFile.ReadLine())
The data that is read is considered to be text so you should use Val to convert it to a numeric value if necessary.
Don't forget to close the text file when you're finished using it.
inputFile.Close()
- A random access file is different from
a sequential access file in that the computer organizes the data in records
that have the same size. We will
not be using random access files in this course but they are very convenient
in professional VB programming. A random access file is like a database (e.g.
Microsoft Access, FileMaker Pro, or SQL). Each record contains multiple fields
such as first_name, last_name, phone_number, etc. The space reserved for
each person's first_name is the same even if one person's name is a lot shorter
than another's. A bit of space is wasted in a random access file but it allows
a programmer to instantly look up and read any record no matter where it
is in the file. Unlike a sequential access file, the records do not have
to be read or written in sequential access but rather "random access".
A random access file is like a CD or DVD. You can immediately play any track
or chapter at any time. Even a DVD seems better than a videocassette tape,
in computer programming depending on the situation, it can be more efficient
sometimes to use a sequential access file rather than a random access file
to save space.