Recipe 12.24. Locking a File During Access


Problem

You need to update the content of a file, and you don't want anyone else messing with it while you're in there.

Solution

The 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.

Discussion

The 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:


FileShare.None

The file cannot be opened by any other process, or even by other open requests within this same process.


FileShare.Read

Other processes can open the file for reading only, not for modification.


FileShare.ReadWrite

Other processes can open the file for both reading and writing. This is the default setting if you exclude the FileShare option from the opening of the stream.


FileShare.Write

Other processes can open the file for writing or appending, but they cannot read from it until this process closes the file.

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) 




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net