Professional Documents
Culture Documents
Methods for VB
.NET
Introduction
So far, we have relied on GUI-based Input/Output…
By using VB .NET controls…
For Data Input to our programs:
= Data Entry
TextBox (our basic input tool, so far)
CheckBox, OptionBox, etc (later)
For Data Output from our programs:
= Data Displaying
Label (our basic output tool)
ListBox
However, we may also use Files for I/O…
These provide a means for long term storage of results.
Using Files for Input / Output
The process of using files for Data I/O is called File Handling.
This requires not only methods for reading and writing data…
But also methods for Opening and Closing files.
VB .NET provides a number of pre-defined methods for File Handling.
The syntax for a general file-handling ‘block’ is as follows:
FileOpen( Integer file_number , String file_name , open_mode )
Some Data Processing ( e.g., writing to or reading from a file )
FileClose( file_number )
Note: this is not a block in the formal sense (for scope).
FileOpen() opens a file, according to mode open_mode…
This must be done before reading or writing.
Ex: file_name = “myfile.txt”
Every open file must be assigned a unique integer file number.
Ex: file_number = 1
FileClose( ) closes the file, after the processing job is finished,.
Modes of File Handling
Opening Files for Sequential Access
Reading/Writing one stored text data piece at a time…
Usually, elements are separated by commas (comma-delimited).
FileClose( file_number )
Here, saved_data is the single piece of data (text) to save.
Example: Writing to a File
Example: Writing to a File (cont.)
Methods for Writing to a File
Print( file_num, param_array ) –formatted output to fileName
param_array is 0 or more comma-separated Objects for formatted output.
…or…
var_name = LineInput ( file_number ) ‘reads and returns one file line
FileClose( file_number )
Here, var_name is a variable used to store input data.
Example: Reading from a File
To read the whole file, one data element at a time we add a loop:
Which loops Until the End Of File 1 is reached (EOF(1) = True).
During each loop, Input() gets one data element, and hands it to word
Note: Input() reads data separated by commas or line-breaks (omitted).
Here, vbCrLf has been used to request a new-line + the typed text.
The FreeFile Function
In VB .NET you must specify the file number, to open a file.
This file number must differ from that of every other open file.
You may use the FreeFile() function to automatically:
Get and Return the number of the next available Free File.