XmlDocument :: Save () adds xml to file

I want to save one XmlDocument object in a class and let the 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 creates two copies of the xml structure inside the file.

+6
c # xmldocument
source share
4 answers

Try

 fs.SetLength(0); 

before saving the call

+3
source share

Add

 fs.Position = 0; 

before calling Save.

+2
source share

It seems a little strange that the fs.Position from the Foole solution does not work.

Equivalent would be

 fs.Seek(0, SeekOrigin.Begin); 

As an alternative

instead of using the same stream:

  //OrigPath is the path you're using for the FileReader System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(OrigPath); xmlDoc.Save(writer); writer.Close(); 
0
source share

Alternatively, even this will work ...

  XmlDocument xmlDoc = new XmlDocument( ); xmlDoc.Load( @"D:\Diary.xml" ); //.... make some changes here XmlText node = xmlDoc.CreateTextNode( "test" ); xmlDoc.DocumentElement.AppendChild( node ); xmlDoc.Save( @"D:\Diary.xml" ); 
0
source share

All Articles