sushi7777
sushi7777

Reputation: 189

C# XMLDocument Save - Process cannot access the file because it is being used by another process

I'm having trouble saving my XML file after I have called load. This function is called twice - once when "toSave" is set to false, and then the second time is when it is set to true. On the second time round, the save causes an exception. I tried adding a Dispose and Close call to the XMLReader but nothing seems to help. Here is the code:

// Check if the file exists
if (File.Exists(filePath))
{
    try
    {
        // Load the file
        XmlReaderSettings readerSettings = new XmlReaderSettings();
        readerSettings.IgnoreComments = true;
        XmlReader reader = XmlReader.Create(filePath, readerSettings);

        XmlDocument file = new XmlDocument();
        file.Load(reader);

        XmlNodeType type;
        type = file.NodeType;
        if (toSave)
            ModifyXMLContents(file.FirstChild.NextSibling, null);
        else
            PopulateNode(file.FirstChild.NextSibling, null);

        // Save if we need to
        if (toSave)
            file.Save(filePath);

        reader.Dispose();
        reader.Close();
    }
    catch (Exception ex)
    {
        // exception is: "The process cannot access the file d:\tmp\10.51.15.2\Manifest.xml" because it is being used by another process
        Console.WriteLine(ex.Message);
    }
}

Any help would be greatly appreciated.

Upvotes: 1

Views: 4071

Answers (2)

Sean B
Sean B

Reputation: 11607

For me this was caused by the file being written out into a directory with MANY (100k) other files. Once I cleared out all the other files the problem went away. NTFS appears to get cranky with very large numbers of files in a single folder.

Upvotes: 0

steve16351
steve16351

Reputation: 5812

The XmlReader you created is still open when you try to save it, and hence it is locking the file and preventing the save.

Once loaded into the XmlDocument, you don't need the reader anymore, so you can close/dispose it before you attempt the save and then the save should work.

For example:

XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;            

XmlDocument file = new XmlDocument();

using (XmlReader reader = XmlReader.Create(filePath, readerSettings))            
    file.Load(reader);

/* do work with xml document */

if (save)
    file.Save(filePath);

Upvotes: 4

Related Questions