简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM