Recipe 12.18. Reading and Writing Binary Files


You need to read or write binary content in a file.


If you have a block of bytes that you want to push out to a file quickly, use the My.Computer.FileSystem.WriteAllBytes() method:

 Dim fileData( ) As Byte ' ----- Fill in the array with relevant data, and then… My.Computer.FileSystem.WriteAllBytes( _    outputFilePath, fileData, False) 

The third argument indicates whether the new data should be appended to the end of any existing file data. If you set it to False, any existing data is replaced by the new data.

To get the binary data back into a Byte array from a file, use the related ReadAllBytes() method:

 Dim fileData( ) As Byte = _ My.Computer.FileSystem.ReadAllBytes(inputFilePath) 


If you need to do more than just read and write the file en masse with a Byte array, consider using the BinaryReader and BinaryWriter classes. These classes wrap a basic Stream object (such as a FileStream), providing convenient methods to read and write content.

The BinaryWriter object provides a single massively overridden Write() method that lets you save most of the core Visual Basic data-type values to a stream. This code opens/creates a file and writes out some basic values:

 Dim value1 As Integer = 5 Dim value2 As Boolean = True Dim value3 As Char = "A"c Dim outStream As New IO.  FileStream( _    "c:\data.dat", IO.FileMode.OpenOrCreate) Dim outFile As New IO.BinaryWriter(outStream) outFile.Write(value1) outFile.Write(value2) outFile.Write(value3) outFile.Close( ) outStream.Close( ) 

Read back this data using a BinaryReader:

 Dim value1 As Integer Dim value2 As Boolean Dim value3 As Char Dim inStream As New IO.  FileStream( _    "c:\data.dat", IO.FileMode.Open, IO.FileAccess.Read) Dim inFile As New IO.BinaryReader(inStream) value1 = inFile.ReadInt32( ) value2 = inFile.ReadBoolean( ) value3 = inFile.ReadChar( ) inFile.Close( ) inStream.Close( ) 

If you need an even higher level of control, the FileStream object (as derived from the Stream class) also exposes ReadByte( ) and WriteByte( ) methods (and other related methods) that let you read and write individual bytes at any position in the file.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400 © 2008-2017.
If you may any questions please contact us: