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");
     }
6
  • is this file used by only single application ? Commented Aug 12, 2015 at 9:51
  • stackoverflow.com/questions/1025407/… Commented Aug 12, 2015 at 9:55
  • yes. it's the only application that uses this method. Commented Aug 12, 2015 at 13:50
  • You need to use lock while load and save file... Commented Aug 13, 2015 at 7:07
  • sounds good. but how do i do this? Commented Aug 13, 2015 at 12:40

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
another location means ? you added lock everywhere with the same object right ?
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.