File Streams & Sequential Data Files
StreamWriter Class

Data is stored in files.

Files are stored on some permanent secondary storage device

Some files are - Text files

Some text files are free form files – No particular format  (a

Other text files contain records. Records are made up of fields.

Fixed-Field files – Each field is fixed in length
         or
Delimited files – If more than one fields is recorded on a line the field values are separated by a specified character (often commas)

 

Sequential data files are files that are read or written in order from the first record until the last. Some files are random files. The records in random files may be accessed in any order or randomly.

We are going to work with sequential text files.

For a program to save data to a sequential disk file it must

Visual Basic uses streams to handle files. A stream sends data as a series of bytes from one location to another. We will use the StreamWriter object to write data to a file and the StreamReader object to input data from a file. The stream objects are located in the System.IO namespace. Since the System.IO namespace is not automatically included in a Visual Basic solution we must Import it.
 
The import statement is placed before the statement declaring the form’s class.
 

Imports System.IO

Public Class Form1

We must declare the Stream object before we can use it

Dim objOutputFile As StreamWriter

To open an output file

objOutputFile = New StreamWriter ("Friends.txt")

 

A file specifier must be supplied to locate the file. If no path is specified the current default directory is assumed. The file specifier may be provided as a constant or as a variable

objOutputFile = New StreamWriter (strFileName)

 

An optional Boolean argument indicates records will be Appended to the end of the file if it is an existing file

objOutputFile = New StreamWriter (strFileName, True)

 

We can use the WriteLine method of the stream writer object to output data one element at a time to a file.

 
 objOutputFile.WriteLine(strCurName)
 objOutputFile.WriteLine(strCurInfo)

 

Or to output data one record at a time.

 objOutputFile.WriteLine(strCurName & “,” & strCurInfo)

 

When we no longer need the file we release the system resources used by the file with the  Close method.

objOutputFile.Close()