Visual Basic Concepts

Using Binary File Access

See Also

The File System Object model does not provide binary file creation or access methods. If you need to create or read binary files, this information will help you do so.

Binary access gives you complete control over a file, because the bytes in the file can represent anything. For example, you can conserve disk space by building variable-length records. Use binary access when it is important to keep file size small.

Note   When writing binary data to a file, use a variable that is an array of the Byte data type, instead of a String variable. Strings are assumed to contain characters, and binary data may not be properly stored in String variables.

Opening a File for Binary Access

To open a file for binary access, use the following syntax for the Open statement:

Open pathname For Binary As filenumber

As you can see, Open for binary access differs from Open for random access in that Len = reclength is not specified. If you include a record length in a binary-access Open statement, it is ignored.

Storing Information in Variable-Length Fields

To best appreciate binary access, consider a hypothetical Employee Records file. This file uses fixed-length records and fields to store information about employees.

Type Person
   ID               As Integer
   MonthlySalary      As Currency
   LastReviewDate      As Long
   FirstName         As String * 15
   LastName            As String * 15
   Title            As String * 15
   ReviewComments      As String * 150
End Type

Regardless of the actual contents of the fields, every record in that file takes 209 bytes.

You can minimize the use of disk space by using binary access. Because this doesn’t require fixed-length fields, the type declaration can omit the string length parameters.

Type Person
   ID               As Integer
   MonthlySalary      As Currency
   LastReviewDate      As Long
   FirstName         As String
   LastName            As String
   Title            As String
   ReviewComments      As String
End Type

Public Empl As Person      ' Defines a record.

Each employee record in the Employee Records file now stores only the exact number of bytes required because the fields are variable-length. The drawback to binary input/output with variable-length fields is that you can’t access records randomly — you must access records sequentially to learn the length of each record. You can seek directly to a specified byte position in a file, but there is no direct way to know which record is at which byte position if the records are of variable length.

For More Information   For additional information on binary file access, see "Open Statement."