- 1 year ago
FileLock for two exclusive processed
Comment
1 / 1
To implement a file lock that allows two exclusive processes, you can use the FileShare.None
parameter in the FileStream
constructor. This will prevent other processes from reading or writing to the file while the lock is held. Here's some sample code that demonstrates this:
csharpusing System.IO;
// Open the file with exclusive access
using (var fileStream = new FileStream("file.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
// Lock the entire file
fileStream.Lock(0, fileStream.Length);
// Do exclusive processing here
// Unlock the file
fileStream.Unlock(0, fileStream.Length);
}
In this code, the FileMode.OpenOrCreate
parameter opens the file if it exists, or creates it if it does not. The FileAccess.ReadWrite
parameter specifies that the file can be read from and written to. Finally, the FileShare.None
parameter prevents other processes from accessing the file while it is locked.
Inside the lock, you can perform any exclusive processing that needs to be done on the file. Once you are finished, call the Unlock
method to release the lock.