VB.NET BinaryWriter Example

Use the BinaryWriter type from System.IO to write a binary file. Call the Write Subroutine.

BinaryWriter creates a binary file. This file contains a certain layout of bytes. With BinaryWriter, we write individual bytes, integers or strings to a file location. This makes possible the creation of files in certain formats.BinaryReaderFile

An example. First, this example creates an array of twelve integers on the managed heap. 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 Each, For
VB.NET program that uses BinaryWriter 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. This is equal to the length of twelve four-byte integers.

Result: The file "file.bin" is created in the current directory. It contains some data.

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 provides a way to easily create specific file formats and layouts using an imperative programming style. Because you can write parts individually, you do not need to construct the entire result in memory before you begin.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to