How to deserialize xml for an object without locking the file?

I have an xml file that I use for the database, which means the xml is updated frequently. There is a FileWatcher for the xml database, and after updating the xml, I get an event, and then I deserialize the xml into an object and check if there were any changes.

The problem I have is that as soon as I deserialize the xml, Stream Reader blocks the file, so I can get exceptions when I try to update it.

Is it possible to deserialize xml without locking the file?

XmlSerializer serializer = new XmlSerializer(typeof (MyType)); Stream reader = new FileStream(File, FileMode.Open); var myType = (MyType) serializer.Deserialize(reader); 
+4
source share
2 answers
 new FileStream(File, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 

FileShare.ReadWrite is the key. Please remember to include filestreams in the expression expression!

Edit: according to the comments (thanks!) There is still a problem if another file writing process requires FileShare.None. This could very well be in the case of a writer. If so, the only solution is to work with individual files. I would suggest renaming the file from the file "file.dat" to "file_readonly1.dat" at the first access after writing. Your reading processes can read the file as many times as they want without blocking the write. The writer will simply create a new file the next time it starts. When some reader sees the new file "file.dat", he will rename it to "file_readonly2.dat". From now on, readers should use a newer version of the file. And so on. I think this circuit is 100% safe.

+6
source
 string xmlString = string.Empty using (StreamReader reader = new StreamReader("xmlfile.xml")) { xmlString = reader.ReadToEnd(); // after leaving the using scope the streamreader is disposed freeing the file } // if the serializer needs a TextReader then you can wrap it here StringReader strReader = new strReader(xmlString); var xmlObject = (MyType) serializer.Deserialize(strReader) 
+1
source

Source: https://habr.com/ru/post/1397313/


All Articles