BinaryWriter
This creates a binary file. The file may contain a certain layout of bytes. With BinaryWriter
, we write individual bytes, integers or strings to a file location.
It is important to include System.IO
when we want to use BinaryWriter
. This makes accessing File.Open
and the BinaryWriter
type itself easier.
First, this example creates an array of twelve integers. These integers will be written one-by-one to the file. Next, a Using statement encloses a BinaryWriter
instance.
File.Open
method is used to create the "file.bin" file, and this is passed to the BinaryWriter
constructor.For Each
loop simply writes each element in the array to the file.Imports System.IO Module Module1 Sub Main() ' Write this array to the file. Dim array() As Int32 = {1, 4, 6, 7, 11, 55, 777, 23, 266, 44, 82, 93} ' Create the BinaryWriter and use File.Open to create the file. Using writer As BinaryWriter = New BinaryWriter(File.Open("file.bin", FileMode.Create)) ' Write each integer. For Each value As Int32 In array writer.Write(value) Next End Using End Sub End Module
When you run this example, look at the current directory of the executable and check the file size of the "file.bin" file. It will be 48 bytes.
byte
integers. This tells us that the BinaryWriter
worked as expected.BinaryReader
When you use BinaryWriter
, you will often also want to use BinaryReader
to read in the files you create. The 2 types make a good pair—they are both in System.IO
.
BinaryWriter
can create specific file formats. Because you can write parts individually, you do not need to construct the entire result in memory before you begin.