如何正确打开 FileStream 以与 XDocument 一起使用
我想使用 Linq2XML 将一些节点附加到 xml 文档。 有问题的文件正在被其他进程使用,他们应该能够在我更新文件时读取该文件。 所以我想出了这个解决方案,这显然不是正确的方法(方法 doc.Save() 失败并说另一个进程正在使用该文件):
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
doc = XDocument.Load(new StreamReader(fs));
doc.Root.Add(entry);
doc.Save(filename);
fs.Close();
}
非常感谢任何帮助。
I want to append some nodes to an xml document using Linq2XML. The file in question is being used by other processes and they should be able to read the file while I update it. So I came up with this solution, which obviously isn't the correct way (The method doc.Save() fails and says that another process is using the file):
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
doc = XDocument.Load(new StreamReader(fs));
doc.Root.Add(entry);
doc.Save(filename);
fs.Close();
}
Any help is greatly appreceated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
加载文档,关闭流,然后再次保存。 这也意味着您可以以更简单的方式打开它:)
Load the document, close the stream, save it again. That also means you can open it in a simpler way :)