VB File I/O

Working with Files in VB
A file is a collection of information saved under a single name. Files assist in managing and organizing data, they also assist in allowing users to store data for long periods on secondary storage.

When you are developing an application software using Visual Basic, it is more helpful if the project you are developing has the capability to read and write information to a disk file. The information (to be written or read) could be computed data or may even be information that is entered into a Visual Basic object (like a text box or list box).

Visual Basic supports two primary file formats: sequential files and random file and access.

A sequential file
It is a file containing a line-by-line list of data. These type of file can be viewed with any text editor. However, when you are using sequential files, you need to know the order in which information has been written to the file beforehand in order to allow the proper reading of the information from the file.

Sequential files can handle both text data and variable values.

Sequential file access is most preferrably used when dealing with files that have lines containing mixed information of different lengths in them.

Sequential File Output (Variables)
When working with sequential files, the first step is to Open the file that you want to write information to or read information from.

This is done using the open statement.

Writing information to a Sequential file
Syntax: Open NameofFile For Output As #FileNunber Example: Open "TestExample.Txt" For Output As #1
 * 1) NameofFile: is the name of the file to you want to open (you need to specify the complete path to the file.
 * For: is a keyword that must be specified.
 * 1) Output: This is the type of operation to be performed. In this case the operation is output.
 * 2) FileNumber: is an integer number that you assign to the file.

When the writing process has completed, Close the file using the Close command.

Syntax: Close FileNumber After a file has been closed, it is saved on the disk under the path and filename specified after the open statement of the file.

Information is written to a sequential file one line at a time and each line of output requires a separate Visual Basic statement.

There are two ways to write data to a sequential file: 1. Using the Write statement: Write #FileNumber, [variable list] where the variable list contains variable names separated by commas and if with string variables then the stings are enclosed in quotes. when the variable list is omitted, a blank line is printed to the file. This format can be used in exporting files to other applications(e.g Excel). Example: private sub cmdFileExport_click Dim Mark As Integer, myName As String,class As String average As Single, age As Integer Open “c:\Example.txt” For Output As #1 Write #1, myName, age, class Write #1, Mark, average Close #1 End sub When above code is executed, if the file (Example.txt) does not exist, then it will be created. When populated, it will have two lines. The first line will be comprised of the variables myName, age and class, delimited by commas, with myName (which is a string variable) displayed in quotes. The second line will simply contain the value of the variables Mark and average.

2. using the Print statement:

Another method of writing variables to a sequential file is by using the Print statement. Print #FileNumber, [variable list] When applied, this statement will write one line of information to the specified file, that is the line containing the variables specified in the variable list. (if the variable list is omitted, then a blank line will be printed.) When the variables in the list are separated with semicolons, then they are printed with a single space between them in the file (in VB, the semocolon is a space separator). When variables are separated by commas, then they are spaced in wide spaces (the comma is a tab separator).

The Print statement does not enclose string variables in quotes, hence,when such a variable is read back into the program, Visual Basic may have trouble identifying the beginning and ending of the string. It is advisable to concatenate quotes to string variables when using the Print statement. Example: Private sub cmdFile_KeyPress(Key ASCII As Integer) Dim A As Integer, B As String, C As Single, D As Integer Open OutputExample For Output As #1 Print #1, A; Chr(34) & B & Chr(34), C  Print #1, D   Close 1 End Sub

Sequential File Input (Variables)
When reading variables from a sequential file, then this will be essentially the reverse of the write procedure. First, open the file using the Open statement by specifying the type of operation that we want to perform. Example: Open SeqFileName For Input As #FileNumber FileNumner is an integer file number SeqFileName is a complete file path. When the operation is complete, then the file is closed using "close". Example: Close N The Input statement is used to read variables from a sequential file into the program. Example: Input #FileNumber, [variable list] The variable names in the list are also separated by commas, if no variables have been listed, the current line in the file FileNumber is skipped. Variables must be read into the program in the same manner as they were written into the file. Example: Input #1, A, B, C Input #1, D The first line of the above code will input values into variables A, B, and C extracted from the first line in the file and the second line reads values into variable D from the second line. When reading data, it doesn’t matter whether the data was originally written to the file using Write or Print. Example: Private Sub Form_Click Dim A As Integer, B As String, C As Single, D As Integer Open "TestExample.Txt" For Input As #1 Input #1, A, B, C   Debug.Print "A="; A    Debug.Print "B="; B    Debug.Print "C="; C    Input #1, D    Debug.Print "D="; D    Close 1 End Sub

Writing and Reading Text Using Sequential Files
In some cases you might want to save text information into a file and retrieve it later for reference purpose. Such information could be a text file created by an application or the contents of a Visual Basic control (such as a text box). Writing Text Files: When writing a sequential text file, then we can follow the simple procedure: When the file is a line-by-line text file, then each line of the file is written to disk using its own single Print statement: Print #FileNumber, Line Line is the current line (a text string). Such a statement should be written in a loop that encompasses all lines of the file. This implies that know the number of lines in your file, before creating the loop code. If you want to write the contents of the Text property of a text box named txtEmpDetails to a file, you can use: Print #FileNumber, txtEmpDetails.Text Example If we have a text box named txtEmpDetails and we want to save the contents of the Text property of that box in a file named Employees.ned on the local drive c: in the \EmploymentDetails directory. Then we can create the code to perform this as below. Example code: Open "c:\EmploymentDetails\Employees.ned" For Output As #1 Print #1, txtEmpDetails.Text Close 1
 * 1) open the file.
 * 2) write to the file.
 * 3) close the file.

Reading Text Files:
In order for us to read the contents of a previously saved text file, then we follow similar steps as those of the writing process: If the file is a text file, then we read each individual line of information using the Line Input command. Example: Line Input #1, Line This type of statement is usually placed in a Do/Loop structure that is repeated untill all lines of the file have been read in. The EOF function may be used to detect an end-of-file condition, This is used when the number of lines in the file are unknown.
 * 1) open the file
 * 2) read from the file
 * 3) close the file.

In order to place the contents of a file opened with number FileNumber into a text box named txtEmpDetails, then we can use the Input function: txtEmpDetails.Text = Input(LOF(FileNumber), FileNumber) This Input function has two arguments: LOF(FileNumber), the length of the file opened as FileNumber and FileNumber, as the file number. Example: If we have a file named Employees.ned stored on the c: drive in the \EmploymentDetails directory, and we want to read that text file into the text property of a text box named txtEmpDetails. Then the code for this could be as: Example: Private sub txtEmpDetails_Click Open "c:\EmploymentDetails\Employees.ned" For Input As #1 txtEmpDetails.Text = Input(LOF(1), 1) Close 1 End Sub The text from the file is now going to be displayed in the text box named txtEmpDetails.Text.

One characteristic of sequential files is that to access a particular data item then you need to read in all items from the file preceeding the item of interest. This method may work well for small data files of unstructured data, but as for large structured files, this process takes alot of time.

Random Access Files
These files allow non-sequential access. A random access file is compried of a number of records, each record having the same length (and measured in bytes). By knowing the length of each record, then the you can easily determine the beginning of each record. The first record in a random access file is assigned the number 1 (one) i.e Record 1, and not 0 as in Visual Basic array (indices).

A record can be made up of a set of variables, of different data types, that describes some item. The structure of a random access file is: Record 1  Nunber of bytes Record 2  Number of bytes Record 3  Number of bytes Record n  Number of bytes

Some variable types and their length in bytes are: Type 		Length (in Bytes) Integer 		2 Long 		       4 Single 		4 Double 		8 String 		1 byte per character So, for every variable that is in a file’s record, we need to add up the individual variable length’s in order to obtain the total record length. To make it simpler, we can apply user-defined variables. User-Defined Variables These data types group variables of different types into one assembly with a single, user-defined type associated with the group. Such types significantly simplify the use and application of random access files.

The Visual Basic keyword Type signals the beginning of a user-defined type declaration and the words End Type signals the end.

Example: 'Say we want to use a variable that describes people by their name, their city, their height, and their weight. We would define a variable of Type myPerson as follows: Type myPerson psName As String psCity As String psHeight As Integer psWeight As Integer End Type We have only specified a user defined type(UDT) named myPerson, we have not reserved any storage for the data. We have simply described to Visual Basic the layout of the data. The record length is the sum of the lengths of all variables that make up a record. In the above UDT, a problem arises with String type variables. Since it is hard to don’t know their lengths ahead of time. To solve this problem, Visual Basic lets you declare fixed lengths for strings. This then allows you to determine the records length. If we have a string variable named myExample, and we want to limit it to 16 characters, then we use the declaration: Dim StrExample As String * 16 Note that each character in a string uses 1 byte, so the length of such a variable is 16 bytes.

Re-Writing the example: Type Person psName As String * 20 psCity As String * 55 psHeight As Integer psWeight As Integer End Type The record length for this variable type is 79 bytes (20 + 55 +2 + 2).

To open a file named PersonalDetails as File #1, with such records, we would use the statement: Open PersonalDetails For Random As #1 Len = 79 The Get and Put statements are used to read from and write to random access files,respectively. These statements only read or write one record at a time.

Syntax: Get #FileNumber, [RecordNumber], variable Put #FileNumber, [RecordNumber], variable The Get statement is used to read data (in the specified record) from the specified file and then it stores that data in the variable specified, whereas the Put statement writes the contents of the specified variable to the file.

In either case, specifying the record number is optional. If the record number has not been specified, then the next sequential position is used. The variable argument specified in the Get and Put statements is usually a single user-defined variable. Once read in, you obtain the component parts of this variable using the dotnotation. Before writing a user-defined variable to a random access file, the UDT is first instantiated, then the component parts are loaded using the dot-notation see Visual Basic Data Structures.

In particular, you need to do a little cute programming when deleting records from a random access file or when ‘resorting’ records. Using the Open and Save Common Dialog Boxes Note to both write and read sequential and random access files, we need a file name for the Open statement. To ensure accuracy and completeness, it is suggested that common dialog boxes be used to get this file name information from the user.

Create a common dialog box on your form named myFiles, with the CancelError property set equal to True. When this property is True, an error is generated by Visual Basic when the user presses the Cancel button in the dialog box. By trapping this error, it allows an elegant exit from the dialog box when canceling the operation is desired.

Example: The code segment to obtain a file name (fleMyFile with a default extension Ext) for opening a file to read is: Dim fleMyFile As String, Ext As String myFiles.Filter = "Files (*." + Ext + ")|*." + Ext myFiles.DefaultExt = Ext myFiles.DialogTitle = "Open File" myFiles.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist On Error GoTo Dont_Open myFiles.ShowOpen fleMyFile = myFiles.filename Exit Sub Dont_Open: Resume ExitLIne ExitLine: Exit Sub End Sub First, some properties are set such that only the files with Ext (a three letter string variable) extensions are displayed (Filter property), the default extension is Ext (DefaultExt property), the title bar is set (DialogTitle property), and some Flags are set to insure the file and path exist. Error trapping has been enabled to trap the Cancel button. Finally, the common dialog box is displayed and the filename property returns with the desired name. That name is put in the string variable fleMyFile. What you do after obtaining the file name depends on the type of file you are dealing with.

For sequential files, you would open the file, then you read in the information, and close the file.

For random access files, we just open the file at this point. Read and write to/from the file.

Example: Dim fleMyFile As String, Ext As String . .  myFiles.Filter = "Files (*." + Ext + ")|*." + Ext myFiles.DefaultExt = Ext myFiles.DialogTitle = "Save File" myFiles.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist On Error GoTo No_Save myFiles.ShowSave fleMyFile = myFiles.filename . .  Exit Sub No_Save: Resume ExitLine ExitLine: Exit Sub End Sub