Type notes. The BinaryReader can read many kinds of data from a file. It handles Strings, with ReadString. It handles many numeric types, not just Integers. These include Double and Long.
Example. First, the example opens a file called "file.bin" which is in the current directory. If you have no file there, you can create one with the BinaryWriter type, also found in System.IO.
Next To use the BinaryReader you want to enclose it in a Using statement, which ensures correct disposal of system resources.
So We acquire the length of the file, then simply loop through every four bytes using a While-loop, calling ReadInt32 each time.
Tip You can see that 12 integers we read from the file. We see these are the same integers that were written there.
Thus The BinaryWriter and BinaryReader types are used together for perfect compatibility.
' Create the reader in a Using statement.
' ... Use File.Open to open the existing binary file.
Using reader As New BinaryReader(File.Open("file.bin", FileMode.Open))
' Loop through length of file.
Dim pos As Integer = 0
Dim length As Integer = reader.BaseStream.Length
While pos < length
' Read the integer.
Dim value As Integer = reader.ReadInt32()
' Write to screen.
' Add length of integer in bytes to position.
pos += 4
Summary. The BinaryReader type is exceedingly useful. It loads binary data in specific file formats into a VB.NET program. Because it is based on streams, it uses somewhat less memory as well.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2022 (rewrite).