0

When I'm trying to save the XML Document I edited the IOException "file used by another process" occured when I try to save that document. Any ideas how to solve this?

Note: This method is called everytime a new element in the XmlDocument should be written.

    public void saveRectangleAsXMLFragment()
    {
            XmlDocument doc = new XmlDocument();

            doc.Load("test.xml");

            XmlDocumentFragment xmlDocFrag = doc.CreateDocumentFragment();

            String input = generateXMLInput();
            xmlDocFrag.InnerXml = input;

            XmlElement mapElement = doc.DocumentElement;
            mapElement.AppendChild(xmlDocFrag);

            input = null;
            mapElement = null;
            xmlDocFrag = null;

            doc.Save("test.xml");
     }
anastasia2
  • 43
  • 8

3 Answers3

0

Its probably one of your other methods, or other part of the code which opened the file and didnt calose it well. Try to search for this kind of problem.

ArBel
  • 79
  • 10
0
try this if your's application is only access that .xml file

1. Create a Object globally

object lockData = new object();

2.Use than object to lock statement where you save and load xml

lock(lockData )
{
     doc.Load("test.xml");
}   

lock(lockData )
{
     doc.Save("test.xml");
}   
  • the exception still occures. at another location but still. because my programm always calls methods that edit the current xml file in style of the code i wrote above. – anastasia2 Aug 13 '15 at 14:20
  • another location means ? you added lock everywhere with the same object right ? –  Aug 13 '15 at 15:18
0

From Jon Skeet's related answer (see https://stackoverflow.com/a/8354736/4151626)

There seems to be a bug in XmlDocument.Save()'s treatment of the file stream, where it becomes pinned and is neither Closed() nor Disposed(). By taking direct control of the creation and disposition of the stream outside of the XmlDocument.Save() I was able to get around this halting error.

//e.g.
XmlWriter xw = new XmlWriter.Create("test.xml");
doc.Save(xw);
xw.Close();
xw.Dispose();
ergohack
  • 1,268
  • 15
  • 27