This documentation is archived and is not being maintained.

Opening Files for Random Access

Visual Studio .NET 2003

After you create the file, you need to open it to make any modifications.

To open a file for random access

  • Use the FileOpen Function with the following syntax:
    FileOpen(FileNumber, FileName, OpenMode.Random, , , RecordLength)

FileNumber and FileName specify the file number and name of the file to be opened, respectively. RecordLength specifies the size of each record in bytes. If RecordLength is less than the actual length of the record written to the file, an error is generated. If RecordLength is greater than the actual length of the record, the record is written, although some disk space may be wasted. Note that every String variable in Visual Basic stores an ASCII string, and that you must specify the byte length of that ASCII string.

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.

In Declaring Variables for Random File Access, a hypothetical Employee Records database first defined a Person data type and then declared a record variable of that type as well as two other variables for processing records. The following code continues the Employee Records example, demonstrating how to open a random-access file to accept Employee data of user-defined type Person:

Sub Main()
   Dim FileNum As Integer, RecLength As Long, Employee As Person
   ' Calculate the record length.
   RecLength = Len(Employee)
   ' Get the next available file number.
   FileNum = FreeFile
   ' Open the new file with the FileOpen statement.
   FileOpen(FileNum, "MYFILE.DAT", OpenMode.Random, , , RecLength)
End Sub

See Also

Declaring Variables for Random File Access | Editing Files Opened for Random Access | Writing Variables to Records | File Access with Visual Basic Run-Time Functions | Sequential File Access | Binary File Access