stressed
stressed

Reputation: 53

C# write to XML error

I am having trouble writing to my XML file

Here is my code:

path = test.xml


FileStream READER = new FileStream(path, FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
System.Xml.XmlDocument Template = new System.Xml.XmlDocument();
Template.Load(READER);

//WRITE TO XML

FileStream WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); //Set up the filestream (READER) //
Template.Save(WRITER);

It works the first time i click the button but then if i click it again i get the error

xmlexception handle Data at the root level is invalid. Line 87, position 10.

is this because the xml document is not closed? if so how do i go about doing this

Please can someone help me

***** UPDATE *****

I've now gotten it work. Just for those who may also be struggling with this here is my new code:

path = test.xml

using(FileStream READER = new FileStream(path, FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
    System.Xml.XmlDocument Template = new System.Xml.XmlDocument();
    Template.Load(READER);

    //WRITE TO XML

    using(FileStream WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
    {
    Template.Save(WRITER);
    }
}

Upvotes: 0

Views: 1061

Answers (1)

Paul
Paul

Reputation: 36319

Anytime you use the stream api's you need to close & dispose of them. Use the 'using' keyword is helpful, e.g.:

using (FileStream READER = new FileStream(path, FileMode.Open,FileAccess.Read,FileShare.ReadWrite)){
/* ... your processing here */
}

Upvotes: 6

Related Questions