Search code examples
c#ioexceptionxmlreaderxmlwriter

C# WPF XMLReader and XMLWriter System.IO.IOException


I have 2 buttons in a WPF.

The first one writes information into an XML The second one restores it into a List

Write Function:

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();
    }
}

Read Function:

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;
}

When i now alternately read and write after a few times i will get an System.IO.IOException which tells me that the process can not access the XML File because it is used by another process.

I thought i can handle this by setting CloseInput to true on the writer and the reader but it does not work.

Does anyone have an idea?


Solution

  • You already have a using-block on the writer that should automatically close the XmlWriter when the block is left. Adding a using block to the reading code should work

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

    Generally it's good practice to use classes that implement IDisposable with using to make sure, that Dispose is called and all resources are cleaned up.

    Please see the documentation on using.