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()
WriteData()
ReadData()
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.Clear()
Console.WriteLine("Data Entry")
Console.WriteLine()
Do
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.WriteLine()
Console.Write("Continue adding (y/n)?: ")
If Console.ReadLine() = "n" Then
addmore = False
Else
addmore = True
End If
bw.Write(person.initial)
bw.Write(person.surname)
bw.Write(person.age)
Loop While addmore <> False
bw.Close()
fs.Close()
Console.WriteLine()
Console.WriteLine("Data Entry Complete. Press Enter To Continue")
Console.ReadLine()
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.Clear()
Console.WriteLine("Reading File")
Console.WriteLine()
Do
person.initial = br.ReadString()
person.surname = br.ReadString()
person.age = br.ReadInt32()
person.DisplayDetails()
Console.WriteLine()
Loop While fs.Position < fs.Length
br.Close()
fs.Close()
Console.WriteLine("All Data Read.")
Console.ReadLine()
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 | Description |
FileMode.Append | Opens the file if it exists and moves to the end of the file. You cannot read the file using this mode. |
FileMode.Create | Specifies that a new file should be created. If the file exists, it will be overwritten. |
FileMode.CreateNew | Specifies that a new file should be created. An exception occurs if the file exists. |
FileMode.Open | Opens the file if it exists, throws an exception if not. |
FileMode.OpenOrCreate | Opens the file if it exists or creates a new one if it does not. |
FileMode.Truncate | Opens an existing file and wipes its contents. |
Having A Go
- 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.