Opening and Closing Files for Binary Access
Use binary access when it is important to keep file size small. Because binary access doesn't require fixed-length fields, you can conserve disk space by building variable-length records.
To open a file for binary access
- Use the FileOpen Function with the following syntax:
FileOpen(FileNumber, FileName, OpenMode.Binary)
To close a file for binary access
- Use the FileClose Function with the following syntax:
FileClose(FileNumber)
As you can see, opening files for binary access differs from Opening Files for Random Access in that the RecordLength expression is not specified. (If you do include a record length in a binary-access FileOpen function, it is ignored.)
To appreciate binary access, consider the Employee Records example discussed in the Random File Access section. This random-access file uses fixed-length records and fields to store information about employees. As a result, every record in the Employee Records database takes the same number of bytes, regardless of the actual contents of the fields.
You can minimize the size of Employee Records by using binary access. Because you are not required to use fixed-length fields, you can omit the string-length parameters from the type declaration, as in the following code:
Structure Person ID As Integer MonthlySalary As Decimal LastReviewDate As Long FirstName As String LastName As String Title As String ReviewComments As String End Structure Public Employee As Person ' Defines a record.
Each employee record in the Employee Records file now occupies only the exact number of bytes required, because the fields are of variable lengths.
The drawback to binary input/output with variable-length fields is that you cannot randomly access records; you must instead access them sequentially to learn the length of each one. You can still go directly to a specified byte position in a file, but if the fields are of variable length, there is no direct way to know which record is at which byte position.
Security Note When writing to files, an application may need to create a file if the file to which it is trying to write does not exist. To do so, it needs permission for the directory in which the file is to be created. However, if the file already exists, the application only needs Write permission to the file itself. Wherever possible, it is more secure to create the file during deployment and only grant Write permission to that file, rather than to the entire directory. It is also more secure to write data to user directories than to the root directory or the Program Files directory.
See Also
File Access with Visual Basic Run-Time Functions | Sequential File Access | Random File Access | FileOpen Function |FileGet Function |FilePut Function