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.
Save(and consider using ausingblock as well).