Home
VB.NET
BinaryWriter Example
Updated Dec 22, 2023
Dot Net Perls
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.
File
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.
Note The File.Open method is used to create the "file.bin" file, and this is passed to the BinaryWriter constructor.
Finally The For Each loop simply writes each element in the array to the file.
For
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
File size. 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.
And This size is equal to the length of 12 four-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.
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 22, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen