Visual Basic Language Reference  

Lock, Unlock Functions

Controls access by other processes to all or part of a file opened using the Open function.

Public Overloads Sub Lock(ByVal FileNumber As Integer)
. . . 
Public Overloads Sub Unlock(ByVal FileNumber As Integer)

-or-

Public Overloads Sub Lock(_
   ByVal FileNumber As Integer, _ 
   ByVal FromRecord As Long _
)
. . . 
Public Overloads Sub Unlock( _
   ByVal FileNumber As Integer, _ 
   ByVal FromRecord As Long _
)

-or-

Public Overloads Sub Lock( _
   ByVal FileNumber As Integer, _ 
   ByVal FromRecord As Long, _ 
   ByVal ToRecord As Long _
)
. . . 
Public Overloads Sub Unlock( _
   ByVal FileNumber As Integer, _
   ByVal FromRecord As Long, _
   ByVal ToRecord As Long _
)

Parameters

FileNumber
Required. Any valid file number.
FromRecord
Optional. Number of the first record or byte to lock or unlock.
ToRecord
Optional. Number of the last record or byte to lock or unlock.

Exceptions/Errors

Exception type Error number Condition
IOException 52 FileNumber does not exist.
IOException 54 File mode is invalid.

Remarks

The Lock and Unlock functions are used in environments where several processes might need access to the same file.

Lock and Unlock functions are always used in pairs. The arguments to Lock and Unlock must match exactly.

If FromRecord and ToRecord are not supplied, the lock will be for the entire file. If FromRecord is specified but not ToRecord, the single record will be locked/unlocked.

If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by FromRecord and ToRecord.

Example

This example illustrates the use of the Lock and Unlock functions. This example assumes that people.txt is a file containing records of the structure Person.

Structure Person
   Dim Name As String
   Dim ID As Integer
End Structure

Sub PutInLockedFile(ByVal index As Integer, ByVal onePerson As Person)
   Try
      FileOpen(1, "c:\people.txt", OpenMode.Binary)
      Lock(1)
      FilePut(index, onePerson)
      Unlock(1)
      FileClose(1)
   Catch
      ' Error recovery code here.
   End Try
End Sub

See Also

FileOpen Function | IOException