I have an xml file which i use for database, meaning that the xml is updated frequently.
For the xml database have a FileWatcher, and once the xml is updated i get an event and then i deserialize the xml into object and check if there were indeed changes.
The problem that i have is that once i deserialize the xml, the Stream Reader is locking the file so i might get exceptions when trying to update it.
Is there a possibility to deserialize the xml without locking the file?
XmlSerializer serializer = new XmlSerializer(typeof (MyType));
Stream reader = new FileStream(File, FileMode.Open);
var myType = (MyType) serializer.Deserialize(reader);
FileShare.ReadWrite is the key. Please remember to put filestreams into a using-statement!
Edit: According the the comments (thanks!) there is still a problem if the other process writing to the file demands FileShare.None. This might well be the case in case of a writer. If this is the case the only solution is to operate on distinct files. I’d propose that you rename the file from “file.dat” to “file_readonly1.dat” on the first access after the write. Your reading processes can then read the file as many times as they want without blocking off the writer. The writer will just create a new file the next time it runs. Once some reader sees the new “file.dat” it will rename it to “file_readonly2.dat”. From then on readers should use the newer version of the file. And so on. I think this scheme is 100% safe.