I have a simple c# function that creates a basic XML file and saves:
private void CreateXMlFile(string Filename, string Name, string Company)
{
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode licenseNode = doc.CreateElement("license");
doc.AppendChild(licenseNode);
XmlNode node = doc.CreateElement("Name");
node.AppendChild(doc.CreateTextNode(Name));
licenseNode.AppendChild(node);
node = doc.CreateElement("Company");
node.AppendChild(doc.CreateTextNode(Company));
licenseNode.AppendChild(node);
doc.Save(Filename);
}
When I try to edit or delete the file I always get following error:
The process cannot access the file because it is being used by another process.
XmlDocument doesnt have any inbuilt dispose or close routines and wondered how I can force the file to close before later editing or deleting it.
I have tried to save the file using StreamWriter:
StreamWriter outStream = System.IO.File.CreateText(outfile);
outStream.Write(data);
outStream.Close();
But this didnt make a difference with the same error.
Your advice is greatly accepted.
Thank you
Your code is fine. I tested it on my machine and there is no lock left after Save().
Try to use Unlocker (http://www.softpedia.com/get/System/System-Miscellaneous/Unlocker.shtml) to check whether you are really the one who holds the lock.
Which .NET framework do you use? Theres also a report (http://bytes.com/topic/net/answers/467028-xmldocument-save-does-not-close-file-properly) which was not reproducable too.
Send Stream to XmlDocument's Save method instead of file name.
I tried executing above code and it is working fine at my end.