I'm writing a C#.NET program which uses XmlSerializer to serialize and deserialize the project the current user is working on to and from an XML file. This is working fine, but I'm trying to figure out a way to prevent two users from opening the same file off a network drive and having one user overwrite the previous user's save. I essentially want the behavior that MS Word has, where if the program can not gain write access to a file when it is being opened it opens the file in a read only mode.
So how do I lock access to a file? Do I just leave a file stream object open and keep a reference to it? Do I continue to use the same filestream object for any intermediate saves rather then opening and closing them for each save? Or is there some other way to lock access to a file?
Also how do I ensure that the file is released even if my app crashes? Would this be a good case to implement IDisposable?