C#写入XML错误 [英] C# write to XML error
问题描述
我无法写入XML文件
这是我的代码:
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句柄根级别的数据无效.第87行,位置10.
xmlexception handle Data at the root level is invalid. Line 87, position 10.
这是因为xml文档未关闭吗?如果是这样,我该怎么做
is this because the xml document is not closed? if so how do i go about doing this
请有人可以帮助我
** * ** 更新 * ** * *
***** 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
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);
}
}
推荐答案
每当您使用流api时,都需要关闭&处理它们.使用'using'关键字很有帮助,例如:
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 */
}
这篇关于C#写入XML错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!