views:

406

answers:

4

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.

+1  A: 

Add:

fs.Position = 0;

before the Save call.

Foole
I tried that but it has a very wierd behavior. Some of the data gets overwritten and the whole file is now not a valid XML file.
A9S6
+1  A: 

Try

fs.SetLength(0);

before Save call

LnDCobra
OK. This worked... Thanks
A9S6
A: 

Hi,

It seems a bit strange that fs.Position from Foole's solution didn't work.

An equivalent would be

fs.Seek(0, SeekOrigin.Begin);

Alternatively

instead of using the same filestream:

            //OrigPath is the path you're using for the FileReader

            System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(OrigPath);
            xmlDoc.Save(writer);
            writer.Close();
Kamal
It will not work, because if the original XML file is 1000 chars long, and after changing the xmldocument it contains only 600 chars left, you will be left with 400 chars at the end of the correct XML file which do not get deleted. Hence why the validation error e.g.original <test><book1></book1></test>you change xmldocument to <test><a></a></test>you will end up with<test><a></a></test>></test>Notice the unnecessary "></test>" at the end
LnDCobra
Right!! UP for @LnDCobra's comment
A9S6
A: 

Alternatively even this would 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" );
Bharath K
Well, this might work but I think it will be much more efficient to just set the length to zero and call Save
A9S6