C# 写入 XML 错误
我在写入 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);
第一次单击按钮时它有效,但如果再次单击它,我会收到错误
xmlexception handle Data at the root level is invalid。第87行,第10位。
这是因为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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每当您使用流 api 时,您都需要关闭 &处理掉它们。使用“using”关键字很有帮助,例如:
Anytime you use the stream api's you need to close & dispose of them. Use the 'using' keyword is helpful, e.g.: