如何正确打开FileStream的用法与一个XDocument如何正确、FileStream、XDocument

2023-09-03 01:32:10 作者:Fairy(仙女)

我要追加一些节点使用Linq2XML XML文档。问题中的文件正被其他进程和它们应该能够读取文件而予更新。所以,我想出了这个解决方案,这显然是不正确的方法(该方法doc.Save()将失败并说另一个进程正在使用的文件):

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();
}

任何帮助是极大AP preceated。

Any help is greatly appreceated.

推荐答案

将文档,关闭流,重新保存。这也意味着你可以在一个更简单的方法打开它:)

Load the document, close the stream, save it again. That also means you can open it in a simpler way :)

XDocument doc;

using (StreamReader reader = File.OpenText(filename))
{
  doc = XDocument.Load(reader);
  doc.Root.Add(entry);
}

doc.Save(filename);