XmlDocument::Save() appends the xml in file

A9S6 picture A9S6 · Feb 25, 2010 · Viewed 20.6k times · Source

I want to keep a single XmlDocument object in a class and let methods make changes to it and save it.

using (FileStream fs = new FileStream(@"D:\Diary.xml", 
       FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fs);

    // ... make some changes here

    xmlDoc.Save(fs);
}

The above code makes two copies of the xml structure inside the file.

Answer

Michal Ciechan picture Michal Ciechan · Feb 25, 2010

Try

fs.SetLength(0);

before Save call