Reputation: 11
I am populating an xml document using c#. If I populate it once then everything is ok but when I try to repopulate it a second time (without closing the program) I get an error message and rubish gets written to the bottom of the xml file.
I'm sure I've found the answer to this question before but I can't find it.
I'm sure its something to do with the fact that I'm not closing something down after updating the xml document or something but I can't remember what exactly I have to close down.
Sorry I hope you all understand. I find it difficult to explain.
Code:
using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
Template.Load(READER); //Load the data from the file into the XmlDocument //
//**********Grab nodes to be written to********
using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
//Set up the filestream (READER) //
//Write the data to the filestream
Template.Save(WRITER);
Upvotes: 0
Views: 141
Reputation: 47968
You read and write in the same file fpath
You have to close the reader after Template.Load(READER);
using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
Template.Load(READER); //Load the data from the file into the XmlDocument //
}
//**********Grab nodes to be written to********
using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
//Set up the filestream (READER) //
//Write the data to the filestream
Template.Save(WRITER);
...
}
Upvotes: 1