C# 写入 XML 错误

发布于 2024-10-20 05:06:38 字数 1166 浏览 5 评论 0原文

我在写入 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

节枝 2024-10-27 05:06:38

每当您使用流 api 时,您都需要关闭 &处理掉它们。使用“using”关键字很有帮助,例如:

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

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 */
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文