开发者

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))
{
    Syst开发者_开发知识库em.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);
    }
}


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 */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜