|
|
Title | Use Visual Basic compatibility functions to quickly read and write an array of integers in a file in Visual Basic 2005 |
Description | This example shows how to use Visual Basic compatibility functions to quickly read and write an array of integers in a file in Visual Basic 2005. |
Keywords | FreeFile, FileOpen, FileGet, FilePut, Visual Basic 2005, VB 2005, VB.NET |
Categories | Files and Directories, VB.NET |
|
|
When the program starts, the form's Load event handler saves references to its TextBoxes in an array for later use. It then determines whether its data file exists. If the file exists, the program uses FreeFile to get an unused file number and calls FileOpen to open the file. It indicates that the file's record size is 4 bytes, the size of a normal Integer.
The program then uses FileGet to read the values from the file into the integers array. It finishes by displaying the integer values.
|
|
Private Const NUM_VALUES As Integer = 10
Const INTEGER_SIZE As Integer = 4
Private m_TextBoxes() As TextBox
' Load saved values.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
m_TextBoxes = New TextBox() {TextBox1, TextBox2, _
TextBox3, TextBox4, TextBox5, TextBox6, TextBox7, _
TextBox8, TextBox9, TextBox10}
' Get the file name.
Dim file_name As String = GetFileName()
' See if the file exists.
If System.IO.File.Exists(file_name) Then
' Open the file.
Dim file_num As Integer = FreeFile()
FileOpen(file_num, file_name, _
OpenMode.Binary, OpenAccess.Read, _
OpenShare.Shared, INTEGER_SIZE)
' Read the array.
Dim integers(NUM_VALUES - 1) As Integer
FileGet(file_num, integers)
' Close the file.
FileClose(file_num)
' Display values.
For i As Integer = 0 To NUM_VALUES - 1
m_TextBoxes(i).Text = integers(i).ToString()
Next i
End If
End Sub
|
|
When the program form is closing, the Closing event handler uses FileOpen to open the data file for writing. It puts the current TextBox values in an Integer array and uses the FilePut method to write the values into the file.
|
|
' Save the current values.
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal _
e As System.Windows.Forms.FormClosingEventArgs) Handles _
Me.FormClosing
' Get the file name.
Dim file_name As String = GetFileName()
' Create the file.
Dim file_num As Integer = FreeFile()
FileOpen(file_num, file_name, _
OpenMode.Binary, OpenAccess.Write, _
OpenShare.Shared, INTEGER_SIZE)
' Write the array.
Dim integers(NUM_VALUES - 1) As Integer
For i As Integer = 0 To NUM_VALUES - 1
integers(i) = Val(m_TextBoxes(i).Text)
Next i
FilePut(file_num, integers)
' Close the file.
FileClose(file_num)
End Sub
|
|
|
|
|
|