Visual Basic .NET File Handling Guide
Visual Basic .NET File Handling Guide
A simple way to store data so that it is accessible the next time you wish to execute the
application is to store it in a data file.
There are three types of data files: binary, sequential and random access.
1
The Visual Basic .NET Coach
Chapter 9 – Files
9.1 Sequential Files
A sequential file allows reading or writing the file from the beginning of the file until the end of
the file.
Files that are read and written sequentially are plain text files commonly known as ASCII files.
ASCII stands for American Standard Code for Information Interchange.
You can view or edit small ASCII files using the Notepad application that comes with Windows,
or you can use a word processor and then select the ASCII option when you save the file.
2
The Visual Basic .NET Coach
Chapter 9 – Files
If you wanted to save the information in your Student Search application a sequential file of
this information might look like one of the following two files:
3
The Visual Basic .NET Coach
Chapter 9 – Files
A fixed-width file contains information formatted so that each line stores each data item in a
fixed location within the line.
The comma-delimited file stores each data item with a comma separating each item.
A comma-delimited file will also place double quotes around String fields.
One uses sequential file access when the application reads all the data at once or writes all the
data at once.
Either a fixed-width or a comma-delimited file can be used.
A comma-delimited file can save space if many of the strings’ average sizes are significantly
smaller than their maximums.
A fixed-width file sets size limits on the fields that are not required with comma-delimited files.
4
The Visual Basic .NET Coach
Chapter 9 – Files
9.2 Fixed-Width Files
Visual Basic .NET provides an object interface for accessing fixed-width formatted files.
You can access a file for both input and output by using a combination of three classes—
FileStream, StreamWriter, and StreamReader.
In order to access these classes, you must include the namespace [Link] with an
Imports statement at the beginning of your file.
5
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files
Step 1: Add the Imports statement to the project at the top of your form.
Imports [Link]
6
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 2: When reading fixed-width files it is easiest to read data from a file one line at a time
and then divide the data read into individual values.
To accomplish this you first must open the text file using the FileStream object.
Dim FileStreamName As New FileStream("Path and File Name", _
[Link], [Link])
FileStreamName is the name of the object that you will use to reference the file from within the
application.
The first parameter is the path to the file and the actual file name of the file that you are
opening.
The second parameter specifies the action upon opening the file: Append, Create,
CreateNew, Open, OpenOrCreate, or Truncate.
Use the Open keyword when opening a file for input and the OpenOrCreate keyword to write
to a file.
The final parameter indicates the action(s) that will be performed upon the file once it is open:
Read, ReadWrite, or Write. Use the Read keyword for input and the Write keyword to write
to a file. When you specify ReadWrite, the file can be either read from or written to. 7
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 3: While the FileStream object will open the file, you need another object to perform an
action on the file.
The two typical actions to perform are reading and writing to the file.
Visual Basic .NET includes two objects, the StreamReader and the StreamWriter.
A StreamReader object allows to read data easily from the file just opened. Instantiating a
StreamReader object requires passing it a FileStream object:
A StreamWriter object allows to write data from the file just opened:
Dim StreamWriterName As New StreamWriter(FileStreamName)
8
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 4: Once you have a StreamReader or StreamWriter object instantiated, you can read
or write a line of data using the following syntax:
strStringVariable = [Link]()
or
[Link](strStringVariable)
In the case of the StreamReader, a line of input is read from the file and stored in a String
variable.
In the case of the StreamWriter, a String variable is passed to the object and written to
the file.
9
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 5a: In order to read data from a fixed-width file, you must divide the single String read
using the ReadLine method of the StreamReader object.
This can be accomplished using the Substring method of the String class.
10
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 5b: In order to write data to a fixed-width file, you must format the data so that the
appropriate number of spaces follow each data element.
The following is what two strings, "Jeff" and "Salvage", each padded to 10 characters,
would look like if they were concatenated together:
"Jeff Salvage "
If the two strings were not padded, but still concatenated, they would look as follows:
"JeffSalvage"
11
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 5b continued: By passing PadRight the maximum size of the String as a parameter,
you can automatically pad the String to the right size.
Observe how you might declare a String, initialize it to "Jeff", and then pad it to 10
characters:
Dim strFirstName As String
strFirstName = "Jeff"
[Link](10)
12
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 5b continued: What would happen if the initial String was initialized as follows?
Dim strFirstName As String
strFirstName = " Jeff"
[Link](10)
The previous code would pad the String so that in the end it contained the following:
" Jeff "
To strip the initial spaces from the front of the String call the Trim method before you call the
PadRight method.
[Link](10)
By calling the Trim and PadRight methods with the size you wish the String to be, the
String will be stripped of any spaces to the left and have the appropriate number of spaces
appended to the right.
To build the String that you will output, you can use the following syntax:
'First data field in the line
strOutputLine = [Link](intstrValue1Size)
14
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Fixed-Width Files Continued
Step 7: The last step in accessing files is to close the objects that access the file (and thus the
file itself) when you are done.
When reading a file, you must close the StreamReader and the FileStream objects.
When writing a file, you must close the StreamWriter and FileStream objects.
All objects can be closed by calling the Close methods of each class. Observe the following
syntax:
[Link]()
[Link]()
or
[Link]()
[Link]()
15
The Visual Basic .NET Coach
Chapter 9 – Files
Example: Fixed-Width Student Grades Application
Problem Description
Previously, you created an application that allowed the user to enter a student’s number,
name, GPA, major, and year.
Each time the application was executed, all the information had to be entered again.
With the use of files, you can store the information you enter in a fixed-width file and then load
it when the application starts.
Problem Discussion
The majority of the application will remain
the same.
The only visible change is that you will add a
Save button to the application to allow any
changes that have been made to the file.
16
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution
1. You must load the information stored in the file so that it may be used by the application.
2. You must allow the user to save the changes made to the data.
To load the information stored in the text file, you can require the user of the application
to take a manual step, like clicking on a button, or you can have the information stored in
the file loaded automatically when the application is executed.
The latter solution is preferable.
3. By placing the code to load information from the file in the form’s constructor, you can be
assured that the information is loaded each time the application is executed.
Your application will store its information in the file [Link] located with the
application in the bin directory so that you do not have to specify a directory for
the file.
17
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
The code opens the fixed-text file and adds a row to the grdStudents MS flex grid for each
line in the input file:
'Student #
[Link] = 0
[Link] = [Link](0, 5).Trim()
'Last Name
[Link] = 1
[Link] = [Link](5, 10).Trim()
18
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
Constructor continued:
'First Name
[Link] = 2
[Link] = [Link](15, 10).Trim()
'GPA
[Link] = 3
[Link] = [Link](25, 5).Trim()
'Major
[Link] = 4
[Link] = [Link](30, 25).Trim()
'Year
[Link] = 5
[Link] = [Link](55, 10).Trim()
Loop
[Link]()
[Link]()
19
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
The other code you must add to your application is the code required to save the data in the
MS flex grid to the text file.
Open the [Link] with a FileMode of OpenOrCreate.
You can output the data in the MS flex grid by looping through each row of the grid, excluding
the first, and building a String containing an entire row’s data.
After a row of data from the MS flex grid is contained in a String, write it to the file with the
WriteLine method of the StreamWriter.
Call the close methods of the StreamWriter and FileStream when you are done.
intCurrentRow = 1
20
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
btnSave_Click continued:
Do While (intCurrentRow < [Link])
'Student #
[Link] = intCurrentRow
[Link] = 0
strOutputLine = [Link](5)
'Last Name
[Link] = 1
strOutputLine &= [Link](10)
'First Name
[Link] = 2
strOutputLine &= [Link](10)
'GPA
[Link] = 3
strOutputLine &= [Link](5)
'Major
[Link] = 4
strOutputLine &= [Link](25)
'Year
[Link] = 5
strOutputLine &= [Link](10)
[Link](strOutputLine)
intCurrentRow += 1
Loop
[Link]()
[Link]()
End Sub 21
The Visual Basic .NET Coach
Chapter 9 – Files
Drill 9.1
Write the code required to read four String values from the fixed-formatted data file
[Link] into four String variables: strString1, strString2, strString3, and
strString4. The maximum size of the four Strings are 10, 20, 15, and 25, respectively.
Answer:
Dim fs As New FileStream("[Link]", [Link], _
[Link])
Dim srDrill As New StreamReader(fs)
Dim strString1 As String
Dim strString2 As String
Dim strString3 As String
Dim strString4 As String
Dim strInputLine As String
strInputLine = [Link]()
strString1 = Trim([Link](0, 10))
strString2 = Trim([Link](10, 20))
strString3 = Trim([Link](1, 15))
strString4 = Trim([Link](1, 25))
[Link]()
[Link]()
22
The Visual Basic .NET Coach
Chapter 9 – Files
Drill 9.2
Write the code required to write four String values to the fixed-formatted data file
[Link] from four String variables: strString1, strString2, strString3, and
strString4. The maximum size of the four Strings are 10, 20, 15, and 25, respectively.
Answer:
Dim fs As New FileStream("[Link]", [Link], _
[Link])
Dim srDrill As New StreamWriter(fs)
Dim strString1 As String
Dim strString2 As String
Dim strString3 As String
Dim strString4 As String
[Link]()
23
[Link]()
The Visual Basic .NET Coach
Chapter 9 – Files
9.3 Comma-Delimited Files
General Access of Comma-Delimited Files
Step 1: Add the Imports statement to the project.
Imports [Link]
Step 2: When reading comma-delimited files, you read data into a series of variables, one for
each field in the file.
You will require a variable for each field in the record that you are reading. It is best to declare
these at the beginning of the code.
24
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Comma-Delimited Files Continued
Step 3: To open the file use the FileOpen function:
FileOpen(FileNumber, "Path and File Name", [Link])
The first parameter, FileNumber, is an Integer used as a handle to the file once it is
opened.
The number must be different from any other file numbers of any other simultaneously opened
files.
The second parameter is the file path to the file that you are opening.
The third parameter specifies the action upon opening the file: Append, Binary, Input,
Output, or Random.
When you wish to read data from a file, use Input; and when you wish to write data to the file,
use Output.
25
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Comma-Delimited Files Continued
Step 4: Once the file is opened, you can either read or write data from the file.
To read data from the file, use the Input function.
Input accepts two parameters.
The first is the file number of the file to read from.
The second is a variable to store the value that is read from the file. Only one value can be
read at a time:
Input(FileNumber, Value)
26
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Comma-Delimited Files Continued
Step 5: To check to see if you have reached the end of a file call the EOF function.
EOF will return True if the file number passed to it is at the end of file.
Otherwise, it will return False.
Step 6: The last step in accessing files is to close the file.
Whether you opened the file for input or output, call the FileClose function with the file
number of the file you wish to close:
FileClose(FileNumber)
27
The Visual Basic .NET Coach
Chapter 9 – Files
Example: Comma-Delimited Student Grades Application
Problem Description
Change the previous application now so it contains the same functionality and ability to save
and load its data, but implement it with a comma-delimited file instead of a fixed-width file.
Problem Discussion
The only two changes required to this application are to the constructor of the form and the
btnSave button’s Click event.
The application would look identical.
28
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution
1. Load the data stored in the file so when the application starts, you have access to the
data.
2. Provide a way for users to save their changes as they feel it is appropriate.
3. Set the loading of the data contained in the file to occur in the constructor of the form.
This way the data is loaded each time the application is executed.
Your application will store its data in the file [Link] located with the application
so that you do not have to specify a directory for the file.
29
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
The code opens the comma-delimited text file and adds a row to the grdStudents MS flex
grid for each line in the input file. Continue reading data from the file until the EOF function
indicates that you have processed the entire file.
You cannot read all of the data elements on a single line of the file in a single command as
before. Instead, you will have to call the Input function for each field in the file.
intStudentFile = FreeFile()
FileOpen(intStudentFile, "[Link]", [Link])
'Student #
[Link] = 0
[Link] = [Link]
'Last Name
[Link] = 1
[Link] = strLastName
'First Name
[Link] = 2
[Link] = strFirstName
'GPA
[Link] = 3
[Link] = [Link]
'Major
[Link] = 4
[Link] = strMajor'Year
[Link] = 5
[Link] = strYear
Loop
FileClose(intStudentFile) 31
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
Add to your application the code required to save the data in the MS flex grid to the text file.
You need to open the [Link] file so that you can write your data to it.
Once your file is open, you can output the data in your MS flex grid by looping through each
row of the grid, excluding the first, and copy each row’s data to individual variables.
After all of the data is written to the file, you must close the file using the FileClose function.
intStudentFile = FreeFile()
FileOpen(intStudentFile, "[Link]", [Link])
intCurrentRow = 1
32
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
btnSave_Click continued:
Do While (intCurrentRow < [Link])
'Student #
[Link] = intCurrentRow
[Link] = 0
intStudentNumber = Val([Link])
'Last Name
[Link] = 1
strLastName = [Link]
'First Name
[Link] = 2
strFirstName = [Link]
'GPA
[Link] = 3
sngGPA = Val([Link])
'Major
[Link] = 4
strMajor = [Link]
'Year
[Link] = 5
strYear = [Link]
'Output the data to the file
WriteLine(intStudentFile, intStudentNumber, strLastName, _
strFirstName, sngGPA, strMajor, strYear)
intCurrentRow += 1
Loop
33
FileClose(intStudentFile)
End Sub The Visual Basic .NET Coach
Chapter 9 – Files
Drill 9.3
Write the code required to read four String values from the comma-delimited data file
[Link] into four String variables: strString1, strString2, strString3, and
strString4.
Answer:
Dim intDrillFile As Integer
Dim strString1 As String
Dim strString2 As String
Dim strString3 As String
Dim strString4 As String
intDrillFile = FreeFile()
FileOpen(intDrillFile, "[Link]", [Link])
Input(intDrillFile, strString1)
Input(intDrillFile, strString2)
Input(intDrillFile, strString3)
Input(intDrillFile, strString4)
FileClose(intDrillFile)
34
The Visual Basic .NET Coach
Chapter 9 – Files
Drill 9.4
Write the code required to write four String values to the comma-delimited data file
[Link] from four String variables: strString1, strString2, strString3, and
strString4.
Answer:
Dim intDrillFile As Integer
Dim strString1 As String
Dim strString2 As String
Dim strString3 As String
Dim strString4 As String
intDrillFile = FreeFile()
FileOpen(intDrillFile, "[Link]", [Link])
FileClose(intDrillFile) 35
The Visual Basic .NET Coach
Chapter 9 – Files
9.4 Random Access Files
Random access files allow you to access data in a file with much flexibility.
You can move forward and back throughout the file reading or writing records as you go.
You must have each record formatted to a single size.
36
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Random Access Files Continued
Step 2: You do not have to choose between opening a file for either input or output.
When you open a file for random access, you can read or write data one record at a time.
The last parameter is the size of the record containing the data to be stored in the file.
The easiest way to determine this is to call the Len function and pass it a variable defined as a
structure defining the record in the file.
37
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Random Access Files Continued
Steps 3 to 5 could occur in any order.
Step 3: To retrieve a specific record from a file, you must first declare a structure,
CurrentStructure, and a variable from that type, RecordStructure.
Read a record specified by an Integer RecordNumber to read a record into the structure
CurrentStructure:
Step 4: To write a structure to the end of the file, you must first declare a structure,
CurrentStructure, and a variable from that type, RecordStructure.
The values you wish to write to the file must be copied to that structure.
You can write the end of the file by specifying a record number one more than the total number
of records currently in the file.
38
The Visual Basic .NET Coach
Chapter 9 – Files
General Access of Random Access Files Continued
Step 5: Updating a record in a random access file is accomplished using the same code as
writing a record initially.
The only difference is that you must make sure that the record number is the same as the one
you wish to update.
Step 6: When you are finished accessing the file, you must close it.
FileClose(FileNumber)
39
The Visual Basic .NET Coach
Chapter 9 – Files
Example: Random Access File Student Grades Application
Problem Description
This application will allow the user to enter a student number, and that student’s information
will be displayed in a series of text boxes.
The user can change the information while the application points to the student’s information.
At any time the user can add a student by entering the new information and then clicking on
the Add Student button.
At any point the user can enter a new student number and retrieve that student’s information.
If the information displayed has been changed and not saved, the changes will be lost.
The application would look like this:
40
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Discussion
You need to declare a structure to store the record of data in a file.
You have to use completely different routines to process the input and output from the file than
in previous examples.
41
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution
You need a few declarations in the Declarations section of the form: a variable that will
store the total number of records within the file, another variable to store the file identification
number of the file you are opening.
This could be hard coded, but it is better programming practice to allow Visual Basic .NET to
pick it for you.
A user-defined type that will provide the details for the format of your record within the file.
Structure StudentRecord
Public intStudentNumber As Integer
<VBFixedString(10)> Public strLastName As String
<VBFixedString(10)> Public strFirstName As String
Public sngGPA As Single
<VBFixedString(20)> Public strMajor As String
<VBFixedString(10)> Public strYear As String
End Structure
42
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
You need to get the file identification number that will refer to your data file from within the
application.
This will be stored in the variable intStudentFile.
Then you must open the actual data file as a random access file.
You need to calculate the total number of records.
This can be accomplished by dividing the length of the file by the length of an individual record
in the file.
The code to add to the form’s constructor is as follows:
intStudentFile = FreeFile()
43
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
To ensure that the file is closed properly, place the code to close the file in the destructor of the
form as shown in the following code:
FileClose(intStudentFile)
44
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
When the butSearch button is clicked, you need to find the record indicated by the
txtSearch text box.
Once the information is gathered into the record, you can copy the contents to each
corresponding TextBox.
45
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
Writing the individual records to the file is a matter of copying the values in the text boxes to
their corresponding fields within the record, incrementing the record counter, and then placing
the actual record in the file.
It’s a good practice to clear the form of the previously entered values.
Private Sub butAddStudent_Click(...
Dim Student As StudentRecord
'Copy values from text boxes to student structure
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
Problem Discussion
Using a random access file would be the poorest choice in this case. If you changed the
problem description so that data was saved as it was changed, then a random access file
format would be the best choice.
With the stipulation that you will only save data upon exiting the application, there is no need
for a random access file format.
The choice is either to use a fixed-format file or a comma-delimited format.
If size isn’t an issue, the fixed-format file is better, because when you open it in Notepad, it’s
easier to read.
Your implementation will follow this format.
48
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution
The constructor code starts as it did before; however, once the MSFlexGrid is formatted, you
must then load the data in the [Link] data file.
You read in each line of data:
divide the line into separate data values
copy those values to their appropriate place in the MSFlexGrid.
'Employee Number
[Link] = 0
[Link] = [Link]
'Employee Name
[Link] = 1
[Link] = [Link](0, 20) 49
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
The constructor continued:
'Hours Worked
[Link] = 2
[Link] = [Link](20, 10)
'Department
[Link] = 3
[Link] = [Link](30, 15)
'Weekly Pay
[Link] = 4
[Link] = [Link](45, 10)
Loop
[Link]()
[Link]()
50
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
The destructor code needs to:
open a file for output
loop through all of the rows in the MSFlexGrid
format each value to its proper size
output the values as a single line to the data file.
51
The Visual Basic .NET Coach
Chapter 9 – Files
Problem Solution Continued
For intCurrentRow = 1 To [Link] - 1
[Link] = intCurrentRow
'Employee Name
[Link] = 1
strOutputLine = PadRight([Link], 20)
'Hours Worked
[Link] = 2
strOutputLine &= PadRight([Link], 10)
'Department
[Link] = 3
strOutputLine &= PadRight([Link], 15)
'Weekly Pay
[Link] = 4
strOutputLine &= PadRight([Link], 10)
[Link](strOutputLine)
Next intCurrentRow
[Link]()
[Link]()
52
The Visual Basic .NET Coach
Chapter 9 – Files
Coach’s Corner
Common Dialog Box
You can use a built-in dialog box that will prompt the user to select a file from any accessible
drive.
It returns a string containing the path and the file name that can be used in your application to
open the file.
Two of the most useful common dialog boxes are the Open File dialog box and the Save
File As dialog box.
53
The Visual Basic .NET Coach
Chapter 9 – Files
Common Dialog Box Continued
While you will place an Open File or Save File As dialog box control on the form, just like
any other control, it will not be visible when you run your application.
Instead, it will appear below the form:
54
The Visual Basic .NET Coach
Chapter 9 – Files
Setting Attributes for a Common Dialog Box
Once a control is placed on the form, you can specify attributes so that your dialog box
behaves exactly the way you desire. Here are the most important ones:
Title: Good application development provides users with directions to help clarify what they
are trying to accomplish.
Filter: By specifying the Filter attribute, you can limit the types of files displayed using
standard file name wildcard patterns.
In order to indicate a filter, you must first specify a description of the limitation as in "Text
Files(*.txt)" and then the actual wildcard pattern to limit the files displayed as in
"*.txt".
These two specifications must be separated by the pipe symbol "|". To set the filter of the
dialog box dlgExample to show only text files, use the following code:
[Link] = "Text Files(*.txt)|*.txt"
InitialDirectory: If this attribute is left unspecified, then the dialog box will be opened using
the current directory.
If you wish the dialog box to open in another directory, specify it by assigning the
InitialDirectory property to the directory path you wish to open.
55
The Visual Basic .NET Coach
Chapter 9 – Files
Open File Example
The following code presents the user with a dialog box to show an Open File dialog box.
It only shows text files and have a title of "Select a Text File".
If you do not select a file, it displays a message to the user and exits the subroutine.
[Link]()
56
The Visual Basic .NET Coach
Chapter 9 – Files
Save File Example
The following code presents the user with a dialog box to show a File Save dialog box.
It only shows text files and has a title of "Save Text File As".
If you do not select a file, it displays a message to the user and exits the subroutine.
[Link]()
MsgBox([Link])
57
The Visual Basic .NET Coach