How to: Read From Binary Files in Visual Basic
The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.
To read from a binary file
Use the ReadAllBytes method, which returns the contents of a file as a byte array. This example reads from the file C:/Documents and Settings/selfportrait.jpg.
Dim bytes = My.Computer.FileSystem.ReadAllBytes( "C:/Documents and Settings/selfportrait.jpg") PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))
For large binary files, you can use the Read method of the FileStream object to read from the file only a specified amount at a time. You can then limit how much of the file is loaded into memory for each read operation. The following code example copies a file and allows the caller to specify how much of the file is read into memory per read operation.
' This method does not trap for exceptions. If an exception is ' encountered opening the file to be copied or writing to the ' destination location, then the exception will be thrown to ' the requestor. Public Sub CopyBinaryFile(ByVal path As String, ByVal copyPath As String, ByVal bufferSize As Integer, ByVal overwrite As Boolean) Dim inputFile = IO.File.Open(path, IO.FileMode.Open) If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then My.Computer.FileSystem.DeleteFile(copyPath) End If ' Adjust array length for VB array declaration. Dim bytes = New Byte(bufferSize - 1) {} While inputFile.Read(bytes, 0, bufferSize) > 0 My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True) End While inputFile.Close() End Sub
Robust Programming
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.
See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
Other Resources
Reading from Files in Visual Basic
Storing Data to and Reading from the Clipboard (Visual Basic)