Home -> Programming -> Storage -> Sequential Data Files

Sequential Data Files

To read or write sequential data files (text files) we need to do the following four things:

  1. Access the File Stream methods which are already writen for us in Visual Basic. To do this we add the statement:
    Imports System.IO
    to the form in which the program file where any of the stream statements are to be coded. This statement must be the very first line of code even before the form declaration!
  2. Declare a new File Stream variable which includes the name of the file to be saved. When a File Stream is declared it causes the following to happen.
    First, space is allocated for the variable.
    Second, a buffer is created as an intermediary between the file and the program.
    The code for this will look like one of the following two examples:
    Coding the name of the file as a literal (It can only be changed later by the programmer)
    Dim aFile as streamreader(Names)
  3. Read and Write the data. This is done using the routines Read and Readline or Write and Writeline.
    ReadLine reads from the file up to and including the next end of line marker (carrage return).
    Read reads the next data element from the file.
    Writeline writes to the file and writes an end of line marker after the element being written.
    Write writes the next element to the file.
  4. Close the file. This is an essential part of the file handling process. To understand why, it helps to understand how buffers operate. When we code to write to a file, the data is written to the buffer instead. Only when the buffer is full is the data written to the disk. So the close statement does three things:
    First, it causes any contents still in the buffer to be written to the file.
    Second, it closes the buffer.
    Third, it releases the file stream variable.
    There is often data left in the buffer which has not yet been written to the file. This is especially true in the case of small files!

The first item is inserted as stated at the beginning of our form. Items 2, 3 and 4 are coded twice, once for the read procedure and once for the write procedure. For example the code to add file loading and saving to a program which has an array of names and phone numbers would look like this. Assume MAX is a constant which sets the arrays size.

  1. Accessing the File Stream Methods


    Imports System .IO

    Public Class Form1

        'form code goes here

    End Class

  2. Create a Procedure to Write to the File


    Private Sub SaveFile
        'Save data to file
        Dim record as Integer

        Dim saveFile as New StreamWriter("Data.txt")    ’File Stream declaration
        For record = 1 to MAX
            saveFile.WriteLine(name(record))                        ’Write the data
            saveFile.WriteLine(phone(record))
        Next record
        saveFile.Close                                                              ’Close the stream
    End Sub

  3. Create a Procedure to Read the File


    Private Sub LoadFile
        'Load data from file
        Dim record as Integer

        Dim loadFile as New StreamReader("Data.txt")    ’File Stream declaration
        Do while loadFile.Peek <> -1
            names(record) = loadFile.ReadLine                      ’Read the data
            phone(record) = loadFile.ReadLine
            record = record + 1
        loadFile.Close                                                                ’Close the stream
    End Sub

Important!

When writing data files the default option is to overwrite the entire file! It is absolutely necessary you remember this! If you wish to add to an existing file you need to use a different form of the StreamWriter method. It looks like this:

Dim saveFile as New StreamWriter("MyFile.txt", True)

The extra parameter in the call is the switch for whether or not the data is appended to, or overwrites the existing file. The default setting for this swith is False, so if the parameter is ommitted, it is assumed by VB that the value is False.

It may at first glance seem that overwriting the file every time you want to save to disk is rather an awkward way to do things. However, we must remember that this is a sequential file and that with such an arrangement of data it is impossible to insert information into the file without rewriting the entire file.

Filenames

Of course we do not want to hard code file names every time we code to read and write a file. That would be limiting in the extreme to have every file named the same way. To start with it would erase the previous file if we saved it in the same location. So instead of entering "Data.txt" the more common practice is to use a variable and code to allow the user to specify the file name and location. The best way to do this is to also use the Common Dialog Boxes, specifically OpenFileDialog and SaveFileDialog, to allow the user to choose which file to open, where to save the files and what the name should be. As a side benefit, this prevents one of the most common errors that used to occur when opening files, that is trying to open a non-existant file. Attempting this will cause and exception to occur and your program to crash. Common Dialog Boxes are more fully explained here.

Saving Files when Using Objects

Object orientd programming has become more and more important. There are several advantages to it but the most important advantage is that programming is accomplished faster when using objects! Since programming consumes a large amount of time, any saving in this area is significant!