Binary File Access in the .NET Framework
- Opening a Binary File
- Working with the File Pointer
- Reading Binary Data from a File
- Writing Binary Data
- Summing Up
A previous article in this series explained how to read and write text files using the .NET framework. This article covers binary files—those files that contain non-character data (graphics, numbers, and so on).
Opening a Binary File
Before you can read or write a binary file, you must open it, which means creating a FileStream object associated with the file. To create the FileStream, you use the following syntax:
Dim fs As FileStream fs = New FileStream( filename , mode, access )
Table 1 describes the arguments for this syntax. Table 2 describes the possible values for mode , including whether the mode can be used for writing, reading, or both.
Table 1 FileStream Arguments.
Argument |
Description |
filename |
The name, including path, of the file to open. |
mode |
A member of the FileMode enumeration specifying how the file should be opened. |
access |
A member of the FileAccess enumeration specifying permitted file access. Possible values are Read, ReadWrite, and Write. |
Table 2 Values for the mode Argument When Creating a FileStream .
FileMode Member |
If the File Exists… |
If the File Doesn't Exist… |
Append |
The file is opened with the pointer positioned at the end of the file. |
A new file is created. |
Create |
The file is overwritten. |
A new file is created. |
CreateNew |
An exception is thrown. |
A new file is created. |
Open |
The file is opened with the pointer positioned at the start of the file. |
An exception is thrown. |
OpenOrCreate |
The file is opened with the pointer positioned at the start of the file. |
A new file is created. |
Let's look at some examples. The following code snippet opens the specified file for appending, meaning that new data written to the file will be appended to the end of the file, after the existing data:
Dim fs As FileStream fs = New FileStream("c:\data\values.dat", FileMode.Append, FileAccess.Write)
The next code sample opens an existing file for reading:
Dim fs As FileStream fs = New FileStream("c:\data\values.dat", FileMode.Open, FileAccess.Read)