BINARYREADER AND BINARYWRITER

The BinaryReader and BinaryWriter classes are not stream classes. Instead, they are helper classes that work with stream classes. They let you read and write data in files using a specific encoding. For example, the BinaryReader object’s ReadInt32 method reads a 4-byte (32-bit) signed integer from the stream. Similarly, the ReadUInt16 method reads a 2-byte (16-bit) unsigned integer.

These classes still work at a relatively low level, and you should generally use higher-level classes to read and write data if possible. For example, you shouldn’t tie yourself to a particular representation of an integer (32- or 16-bit) unless you really must.

BinaryReader and BinaryWriter objects are attached to stream objects that provide access to the underlying bytes. Both of these classes have a BaseStream property that returns a reference to the underlying stream. Note also that the Close method provided by each of these classes automatically closes the underlying stream.

The following table describes the BinaryReader class’s most useful methods.

METHOD PURPOSE
Close Closes the BinaryReader and its underlying stream.
PeekChar Reads the stream’s next character but does not advance the reader’s position, so other methods can still read the character later.
Read Reads characters from the stream and advances the reader’s position.
ReadBoolean Reads a Boolean from the stream and advances the reader’s position by 1 byte.
ReadByte Reads a byte from the stream ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.