Writing to a binary file Learn programming Visual Basic (VB.net)

Lesson:

File Management


Exercise:

Writing to a binary file 14


Objetive:

Create a program which asks the user for his name, his age (byte) and the year in which he was born (int) and stores them in a binary file.

Create also a reader to test that those data have been stored correctly.


Code:

Imports System
Imports System.IO
Class BinaryWriterTest
    Private Shared Sub Main(ByVal args As String())
        Console.Write("Enter your name: ")
        Dim name As String = Console.ReadLine()
        Console.Write("Enter your age: ")
        Dim age As Byte = Convert.ToByte(Console.ReadLine())
        Console.Write("Enter your year of birth: ")
        Dim yearOfBirth As Integer = Convert.ToInt32(Console.ReadLine())
        Dim file As BinaryWriter = New BinaryWriter(File.Open("data.dat", FileMode.Create))
        file.Write(name)
        file.Write(age)
        file.Write(yearOfBirth)
        file.Close()
        Dim datas As String
        Dim datab As Byte
        Dim datai As Integer
        Dim inputFile As BinaryReader = New BinaryReader(File.Open("data.dat", FileMode.Open))
        datas = inputFile.ReadString()
        datab = inputFile.ReadByte()
        datai = inputFile.ReadInt32()
        inputFile.Close()
        Console.WriteLine(datas)
        Console.WriteLine(datab)
        Console.WriteLine(datai)

        If (datas <> name) OrElse (datab <> age) OrElse (datai <> yearOfBirth) Then
            Console.WriteLine("Error in data")
        Else
            Console.WriteLine("Read error")
        End If
    End Sub
End Class