Visual Basic 2010 (Console) Guide
Binary Files

Structure TPerson
   Public initial As String
   Public surname As String
   Public age As Integer
   Public Sub DisplayDetails()
      Console.WriteLine("{0} {1}, {2}", initial, surname, age)
   End Sub
End Structure

Dim path As String = "C:\test.bin"

Sub Main()
End Sub

Sub WriteData()
   Dim fs As FileStream = New FileStream(path, FileMode.CreateNew)
   Dim bw As BinaryWriter = New BinaryWriter(fs)
   Dim addmore As Boolean = False
   Dim person As TPerson = New TPerson()

   Console.WriteLine("Data Entry")

      Console.Write("Enter the initial: ")
      person.initial = Console.ReadLine()
      Console.Write("Enter the surname: ")
      person.surname = Console.ReadLine()
      Console.Write("Enter the age: ")
      person.age = Console.ReadLine()
      Console.Write("Continue adding (y/n)?: ")
      If Console.ReadLine() = "n" Then
         addmore = False
         addmore = True
      End If
   Loop While addmore <> False

   Console.WriteLine("Data Entry Complete. Press Enter To Continue")
End Sub

Sub ReadData()
   Dim person As TPerson = New TPerson()
   Dim fs As FileStream = New FileStream(path, FileMode.Open)
   Dim br As BinaryReader = New BinaryReader(fs)

   Console.WriteLine("Reading File")

      person.initial = br.ReadString()
      person.surname = br.ReadString()
      person.age = br.ReadInt32()
   Loop While fs.Position < fs.Length

   Console.WriteLine("All Data Read.")
End Sub

Look carefully at the lines of code that open the filestreams. The FileMode enumeration specifies what you want to do with the file. There are other modes,

FileMode.AppendOpens the file if it exists and moves to the end of the file. You cannot read the file using this mode.
FileMode.CreateSpecifies that a new file should be created. If the file exists, it will be overwritten.
FileMode.CreateNewSpecifies that a new file should be created. An exception occurs if the file exists.
FileMode.OpenOpens the file if it exists, throws an exception if not.
FileMode.OpenOrCreateOpens the file if it exists or creates a new one if it does not.
FileMode.TruncateOpens an existing file and wipes its contents.

Having A Go

  1. Write a program that reads the CSV file provided on the previous page and creates a binary file with the data. Display all of the records from the binary file that you create.