To prepare your application to write to a binary file, you must set up a BinaryWriter object, with the statement shown here, where FS is a properly initialized FileStream object:
Dim BW As New BinaryWriter(FS)
You can also create a new BinaryWriter class directly on a file with the following form of the constructor:
Dim BW As New StreamReader(path)
To specify the encoding of the text in the binary file, use the following form of the method:
Dim BW As New BinaryWriter(FS, encoding)
Dim BW As New BinaryWriter(path, encoding)
You can also specify a third argument indicating the size of the buffer to be used with the file input/output operations:
Dim BW As New BinaryWriter(FS, encoding, bufferSize)
Dim BW As New BinaryWriter(path, encoding, bufferSize)
The BinaryWriter class exposes the following methods for manipulating binary files.
This method flushes and closes the current BinaryWriter and releases any system resources associated with it.
This method clears all buffers for the current writer and writes all buffered data to the underlying file.
This method sets the position within the current stream. Its syntax is the following, where origin is a member of the SeekOrigin enumeration (see Table 11.6 in section FileStream class) and offset is the distance from the origin:
The Write method writes a value to the current stream. This method is heavily overloaded, but it accepts a single argument, which is the value to be written to the file. The data type of its argument determines how it will be written. The Write method can save all the base types to the file in their native format, unlike the Write method of the TextWriter class, which stores them as strings.
Whereas all other data types can be written to a binary file with the Write method, strings must be written with the WriteString method. This method writes a length-prefixed string to the file and advances the current position by the appropriate number of bytes. The string is encoded by the current encoding scheme, and the default value is UTF8Encoding.
You will find examples of using the Write and WriteString methods of the BinaryWriter object at the end of the following section, which describes the methods of the BinaryReader class.