views:

850

answers:

1

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.

+3  A: 

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);
Jon Skeet
thanks for your answer, jon. if I use this version, can I make sure that other processes can open the same file for read-access?
Matthias
Well, they can't be reading from it when you call Save... is that a problem? I can't remember what File.OpenText does in terms of sharing, but you could easily check and use a StreamReader constructor doing the right thing if necessary.
Jon Skeet