【问题标题】:C# WPF XMLReader and XMLWriter System.IO.IOExceptionC# WPF XMLReader 和 XMLWriter System.IO.IOException
【发布时间】:2017-10-12 08:50:19
【问题描述】:

我在 WPF 中有 2 个按钮。

第一个将信息写入 XML 第二个将它恢复到一个列表中

写函数:

public static void Write(List<string> numbers) {

    XmlWriterSettings myWriterSettings = new XmlWriterSettings();
    myWriterSettings.CloseOutput = true;
    myWriterSettings.NewLineOnAttributes = true;
    using (XmlWriter myWriter = XmlWriter.Create(XMLPathRestore, myWriterSettings)) {

        myWriter.WriteStartDocument();
        myWriter.WriteStartElement("Something");

        //Writing numbers into XML

        myWriter.WriteEndElement();
        myWriter.WriteEndDocument();
        myWriter.Close();
    }
}

读取功能:

public static List<string> Read() {

    List<string> numbers = new List<string>();

    XmlReaderSettings myReaderSettings = new XmlReaderSettings();
    myReaderSettings.CloseInput = true;

    if (File.Exists(XMLPath) == true) {
        XmlReader myReader = XmlReader.Create(XMLPath, myReaderSettings);
        while (myReader.Read()) {
            //Fill List<string> numbers from XML
        }
    }
    return concernNumbers;
}

当我现在交替读写几次后,我会得到一个 System.IO.IOException,它告诉我该进程无法访问 XML 文件,因为它被另一个进程使用。

我认为我可以通过在编写器和阅读器上将 CloseInput 设置为 true 来处理此问题,但它不起作用。

有人有想法吗?

【问题讨论】:

  • 您是否在其他地方打开 XML 文件?

标签: c# ioexception xmlreader xmlwriter


【解决方案1】:

您已经在编写器上有一个using-block,它应该在离开该块时自动关闭XmlWriter。在阅读代码中添加 using 块应该可以工作

using (XmlReader myReader = XmlReader.Create(XMLPath, myReaderSettings))
{
  while (myReader.Read()) {
    //Fill List<string> numbers from XML
  }
}

一般来说,使用实现IDisposableusing 的类来确保调用Dispose 并清理所有资源是一种很好的做法。

请参阅the documentation on using

【讨论】:

    【解决方案2】:

    阅读完毕后关闭阅读器:

    myReader.Close();
    

    【讨论】:

    • 我想说你甚至可以执行 myReader.Dispose(),因为 XmlReader 实现了 IDisposable 接口。这应该是确保您释放对象使用的所有资源的正确方法。
    【解决方案3】:
    using (var reader = XmlReader.Create(XMLPath, myReaderSettings)
    {
        while (myReader.Read()) {
    
        }
    }
    

    using 块将在完成后处理每个读取器实例,我建议您使用using block

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 2012-02-21
      • 2016-06-22
      • 1970-01-01
      相关资源
      最近更新 更多