- Opening a Binary File
- Working with the File Pointer
- Reading Binary Data from a File
- Writing Binary Data
- Summing Up
Working with the File Pointer
Like text files, a binary file has a pointer that indicates the file position at which the next read or write operation will take place. Position is counted in terms of bytes. When a file is opened, the pointer is positioned at the start of the file unless you specified FileMode.Append, which positions the pointer at the end of the file. Read and write operations always move the pointer so it's at the end of whatever was just read or written. You can also move the pointer under program control by using the Seek() method. Here's the syntax:
Seek( offset , origin )
Table 3 describes the arguments.
Table 3 Seek() Arguments.
Argument |
Description |
offset |
The number of bytes to move the pointer. Use a negative value to move toward the start of the file. |
origin |
Specifies whether to start the seek operation at the beginning of the file, the current pointer position, or the end of the file. Possible values for this argument from the SeekOrigin enumeration are Begin, Current, and End. |
Trying to seek to a position before the start of the file causes an exception. Seeking to a position past the end of the file results in the file size being increased as needed, with the new bytes filled with 0.
Table 4 shows some examples of using Seek().
Table 4 Seek() Examples.
Action |
Code |
Seek to the end of the file |
Seek(0, SeekOrigin.End) |
Seek to the start of the file |
Seek(0, SeekOrigin.Begin) |
Move the pointer back 4 bytes |
Seek(-4, SeekOrigin.Current) |
You can call Seek() on a FileStream instance, but more often you'll call it on the associated BinaryWriter or BinaryReader object (explained in the following sections). The result is precisely the same.