Home
VB.NET
BinaryWriter Example
This page was last reviewed on 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 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 Dec 22, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.