O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Read to and Write from a Binary File

Problem

You want to read or write data from a binary file.

Solution

Use the BinaryReader or BinaryWriter to wrap the underlying FileStream.

Discussion

The BinaryReader and BinaryWriter classes provide an easy way to work with binary data. The BinaryWriter class provides an overloaded Write method that takes any basic string or number data type, converts it to a set of bytes, and writes it to a file stream. The BinaryReader performs the same task in reverse—you call methods such as ReadString or ReadInt32, and it retrieves the data from the current position in the file stream and converts it to the desired type.

Here’s a simple code snippet that writes data to a binary file, and reads it back.

' Define the sample data. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required