title: Saving XML stream in C# says that it's being used by another process
body: <p>I have <a href="http://wiki.nazgulled.net/en/easy-settings" rel="nofollow noreferrer">this</a> open-source library that I'm having some trouble fixing a problem... This library allows to easily create an XML file to store application settings. But I'm having an issue saving the changes.</p>
  
  <p>I have another application where I'm using this library and every time that application window is done resizing, I call the Save() method of the library to save the window size/position to the XML file.</p>
  
  <p>Most of times it works fine, everything is saved. Once in a while though, I get an exception saying the file is being used by another process.</p>
  
  <p>I really need to make sure that changes are saved every time the Save() method is called, I need to handle this exception somehow or prevent it from happening.</p>
  
  <p>What are you guys suggestions for best handling this situation?</p>
  
  <p>The code for the Save() method is the following:</p>
  
  <pre><code>public void Save() {
      // Create a new XML file if there's no root element
      if(xDocument.DocumentElement == null) {
          xDocument = new XmlDocument();
          xDocument.LoadXml("&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n" +
              "&lt;" + XmlRootElement + "&gt;\n&lt;/" + XmlRootElement + "&gt;");
      }
  
      // OMITTED CODE WAS HERE (NOT IMPORTANT FOR THE PROBLEM)
  
      // Create a new XML writer for the XML file
      XmlWriter xWriter = XmlWriter.Create(XmlFilePath, new XmlWriterSettings() {
          Indent = true,
          IndentChars = "\t"
      });
  
      // Sort the XML file using the XSL sylesheet and save it
      xslTransform.Transform(xDocument, xWriter);
  
      // Clear the buffer and close the XML writer stream
      xWriter.Flush();
      xWriter.Close();
  }
  </code></pre>