I need to be able to open a file to read it, maintaining a lock that denies other instances of the same application write access until I have written the amended file back to disk. The file is in a shared location on a network, and the app instances can be on any machine on the network.
I have tried using a FileStream with FileAccess.ReadWrite and FileShare.Read, with a Streamreader to read and then a StreamWriter (on the same FileStream) to write, but this corrupts the file. Other permutations of the FileAccess and FileShare don’t seem to solve my basic problem either.
So I tried closing the StreamReader before opening the StreamWriter, but that changes the CanRead and CanWrite properties of the FileStream, so I still can’t write.
Clearly I am taking the wrong approach, so can someone tell me how I should be approaching this? It seems a common enough thing to want to do – edit a file and block write access until the edited file is saved.
If you want to write to a file, you need to take exclusive file access, otherwise other programs can read partially written data (your writes aren’t atomic). There are solutions to this, but they are quite complex.
A solution could be something like this:
where you always keep open the
FileStreamasBefore the
datathere is a “guard byte” that tells if the data is being written. If it’s being written then reads on it will fail. The file is locked “where it’s needed” usingFileStream.Lock.This clearly works better with binary fixed-length data. If you have variable length data (or you need to atomically update more “regions” of a file) then it becomes more complex. Normally you use DBs for this reason 🙂