Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse a BinaryReader and BinaryWriter in loops to read and write an array of integers in a file in Visual Basic 2005
DescriptionThis example shows how to use a BinaryReader and BinaryWriter in loops to read and write an array of integers in a file in Visual Basic 2005.
KeywordsBinaryReader, BinaryWriter, Visual Basic 2005, VB 2005, VB.NET
CategoriesFiles 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 makes a FileStream attached to it and a BinaryReader associated with the FileStream. It then uses the BinaryReader's ReadBytes method to read the file's contents into a Byte array. It calls the BytesToIntegers helper function described shortly to convert the Byte array into an Integer array and then displays the result.
 
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 Exists(file_name) Then
        ' Open the file.
        Dim fs As New FileStream(file_name, FileMode.Open)

        ' Create a BinaryReader for the FileStream.
        Dim binary_reader As New BinaryReader(fs)
        fs.Position = 0

        ' Read the data as a byte array.
        Dim bytes() As Byte = _
            binary_reader.ReadBytes(fs.Length)

        ' Copy the bytes into an integer array.
        Dim integers() As Integer = BytesToIntegers(bytes)
        binary_reader.Close()
        fs.Dispose()

        ' Display values.
        For i As Integer = 0 To NUM_VALUES - 1
            m_TextBoxes(i).Text = integers(i).ToString()
        Next i
    End If
End Sub
 
The BytesToIntegers function copies the memory in a Byte array into an Integer array. First it creates the result array. It allocates a pinned GCHandle object for the destination array. Because the array is pinned, Visual Basic will not move it until the handle is freed.

The program then uses System.Runtime.InteropServices.Marshal.Copy to copy the memory in the Byte array into the Integer array. It frees the Integer array's GCHandle and returns the result array.

 
Private Function BytesToIntegers(ByVal bytes() As Byte) As _
    Integer()
    ' Allocate the integers array.
    Dim integers(bytes.Length \ INTEGER_SIZE - 1) As Integer

    ' Pin the integers array.
    Dim gc_handle As GCHandle = GCHandle.Alloc(integers, _
        GCHandleType.Pinned)

    ' Copy the bytes.
    System.Runtime.InteropServices.Marshal.Copy( _
        bytes, 0, gc_handle.AddrOfPinnedObject, _
        bytes.Length)

    ' Unpin the integers array.
    gc_handle.Free()

    ' Return the result.
    Return integers
End Function
 
When the program's form is closing, the Closing event handler creates a FileStream for the data file and makes a BinaryWriter associated with it. It copies the form's TextBox values into an Integer array and calls helper function IntegersToBytes (described shortly) to copy the memory in the Integer array into a Byte array. It uses the BinaryWriter's Write method to write the bytes 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.
    Using fs As New FileStream(file_name, FileMode.Create)
        ' Create a BinaryWriter for the FileStream.
        Dim binary_writer As New BinaryWriter(fs)

        ' Get the values.
        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

        ' Copy the integers into a byte array.
        Dim bytes() As Byte = IntegersToBytes(integers)

        ' Write the bytes into the file.
        binary_writer.Write(bytes)

        binary_writer.Close()
    End Using
End Sub
 
Function IntegersToBytes is similar to BytesToIntegers except it copies memory from an Integer array into a Byte array.
 
Private Function IntegersToBytes(ByVal integers() As _
    Integer) As Byte()
    ' Allocate the bytes array.
    Dim bytes(integers.Length * INTEGER_SIZE - 1) As Byte

    ' Pin the bytes array.
    Dim gc_handle As GCHandle = GCHandle.Alloc(bytes, _
        GCHandleType.Pinned)

    ' Copy the integers.
    System.Runtime.InteropServices.Marshal.Copy( _
        integers, 0, gc_handle.AddrOfPinnedObject, _
        integers.Length)

    ' Unpin the bytes array.
    gc_handle.Free()

    ' Return the result.
    Return bytes
End Function
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated