使用c#填充xml错误

本文关键字:错误 xml 填充 使用 | 更新日期: 2023-09-27 17:49:43

我正在使用c#填充xml文档。如果我填充它一次,那么一切都是好的,但当我试图重新填充它第二次(不关闭程序),我得到一个错误消息和垃圾被写入xml文件的底部。

我相信我以前已经找到了这个问题的答案,但是我找不到。

我确定这与我在更新xml文档或其他东西后没有关闭某些东西有关,但我不记得我究竟要关闭什么。

对不起,我希望你们都能理解。我觉得很难解释。 代码:

using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
      {
                System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
                Template.Load(READER); //Load the data from the file into the XmlDocument //
                //**********Grab nodes to be written to********

                using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    //Set up the filestream (READER) //
                    //Write the data to the filestream
                    Template.Save(WRITER);

使用c#填充xml错误

您在同一个文件fpath中读写

您必须在Template.Load(READER);

之后关闭阅读器
  using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
       System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
       Template.Load(READER); //Load the data from the file into the XmlDocument //
  }
  //**********Grab nodes to be written to********

  using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
  {
     //Set up the filestream (READER) //
     //Write the data to the filestream
     Template.Save(WRITER);
     ...
  }