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.
Try
fs.SetLength(0);
before saving the call
Add
fs.Position = 0;
before calling Save.
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();
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" );