我想使用 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();
}
非常感谢任何帮助。
最佳答案
加载文档,关闭流,再次保存。这也意味着您可以以更简单的方式打开它:)
XDocument doc;
using (StreamReader reader = File.OpenText(filename))
{
doc = XDocument.Load(reader);
doc.Root.Add(entry);
}
doc.Save(filename);
关于c# - 如何正确打开 FileStream 以与 XDocument 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/277783/