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.