Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlDocument::Save() appends the xml in file

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.

like image 956
A9S6 Avatar asked Feb 25 '10 10:02

A9S6


2 Answers

Try

fs.SetLength(0);

before Save call

like image 88
Michal Ciechan Avatar answered Sep 26 '22 14:09

Michal Ciechan


Add:

fs.Position = 0;

before the Save call.

like image 43
Foole Avatar answered Sep 22 '22 14:09

Foole