简体   繁体   English

如何在不锁定文件的情况下将xml反序列化为对象?

[英]How to deserialize xml to object without locking the file?

I have an xml file which i use for database, meaning that the xml is updated frequently. 我有一个用于数据库的xml文件,这意味着xml经常更新。 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. 对于xml数据库有一个FileWatcher,一旦更新了xml,我得到一个事件然后我将xml反序列化为对象并检查是否确实有变化。

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. 我遇到的问题是,一旦我反序列化xml,Stream Reader就会锁定文件,这样我在尝试更新它时可能会遇到异常。

Is there a possibility to deserialize the xml without locking the file? 是否有可能在不锁定文件的情况下反序列化xml?

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

FileShare.ReadWrite is the key. FileShare.ReadWrite是关键。 Please remember to put filestreams into a using-statement! 请记住将文件流放入using语句中!

Edit: According the the comments (thanks!) there is still a problem if the other process writing to the file demands FileShare.None. 编辑:根据评论(谢谢!)如果写入文件的其他进程需要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. 我建议您在写入后的第一次访问时将文件从“file.dat”重命名为“file_readonly1.dat”。 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". 一旦某个读者看到新的“file.dat”,它会将其重命名为“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. 我认为这个方案是100%安全的。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM