ProblemYou need to update the content of a file, and you don't want anyone else messing with it while you're in there. SolutionThe System.IO. FileStream object can be used to open a file with various levels of file sharing and locking. When opening a file stream, use the appropriate locking flag to keep other users or processes from accessing the file while you have it open. DiscussionThe System.IO. FileStream constructor includes several arguments that indicate how the file should be opened. One of the basic overloads for this constructor uses a file-sharing flag as its fourth argument: Dim newStream As New IO.Stream(path As String, _ mode As IO.FileMode, access As IO.FileAccess, _ share As IO.FileShare) The share argument accepts one of the following System.IO.FileShare enumeration values:
Although the FileShare enumeration indicates whether other processes can open a file while your process is using it, it does not control the authorization of access to this file. The other process must still have security rights to access the file in order to open it, even if you specify FileShare.ReadWrite. When opening files in random mode using the Visual Basic FileOpen() method (see Recipe 12.16), you can lock specific records within the opened file using the Lock() method: ' ----- Open the file. Each record is 50 bytes. Dim fileID As Integer = FreeFile( ) FileOpen(fileID, pathToFile, OpenMode.Random, _ OpenAccess.ReadWrite, OpenShare.LockWrite, 50) … ' ----- Lock record number five. Lock(fileID, 5) … ' ----- Make the needed changes, then unlock the record. Unlock(fileID, 5) … ' ----- Finished with the file. FileClose(fileID) |