• In many applications, we would like to be able to save text information
and retrieve it for later reference. This information could be a text file created
by an application or the contents of a Visual Basic text box.
Writing Text Files:
To write a sequential text file, we follow the simple procedure: open the file,
write the file, close the file. If the file is a line-by-line text file, each
line of the file is written to disk using a single Print statement:
Print #N, Line
where Line is the current line (a text string). This statement should be in
a loop that encompasses all lines of the file. You must know the number of lines
in your file, beforehand.
If we want to write the contents of the Text property of a text box named txtExample
to a file, we use:
Print #N, txtExample.Text
We have a text box named txtExample. We want to save the contents of the Text
property of that box in a file named MyText.ned on the c: drive in the \MyFiles
directory. The code to do this is:
Open “c:\MyFiles\MyText.ned” For Output As #1
Print #1, txtExample.Text
The text is now saved in the file for later retrieval.
• Reading Text Files:
To read the contents of a previously-saved text file, we follow similar steps
to the writing process: open the file, read the file, close the file. If the file
is a text file, we read each individual line with the Line Input command:
Line Input #1, Line
This line is usually placed in a Do/Loop structure that is repeated untill
all lines of the file are read in. The EOF() function can be used to detect an
end-of-file condition, if you don’t know, a prioiri, how many lines are
in the file.
To place the contents of a file opened with number N into the Text property
of a text box named txtExample we use the Input function:
txtExample.Text = Input(LOF(N), N)
This Input function has two arguments: LOF(N), the length of the file opened
as N and N, the file number.
We have a file named MyText.ned stored on the c: drive in the \MyFiles directory.
We want to read that text file into the text property of a text box named txtExample.
The code to do this is:
Open “c:\MyFiles\MyText.ned” For Input As #1
txtExample.Text = Input(LOF(1), 1)
The text in the file will now be displayed in the text box.