Click here to Skip to main content
16,023,339 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have never worked with config files before but now I need to learn fast, so please bear with me if I'm making obvious mistakes or asking silly questions. I try to add new nodes to the config file and hard code their values with the following code;

string pathToConfig = Directory.GetCurrentDirectory();

            // check for the config file
            if (File.Exists(string.Format(@"{0}\config.xml", pathToConfig)))
            {
                Console.WriteLine("Found the config.xml file, reading..");

                // load the xml file
                XmlDocument xmlDoc = new XmlDocument();
                XmlTextReader xmlReader = new XmlTextReader(string.Format(@"{0}\config.xml", pathToConfig));
                xmlDoc.Load(xmlReader);
                XmlElement elem = xmlDoc.CreateElement("XPos");
                XmlText text = xmlDoc.CreateTextNode("400");
                xmlDoc.DocumentElement.AppendChild(elem);
                xmlDoc.DocumentElement.LastChild.AppendChild(text);

                Console.WriteLine("Display the modified XML...");
                xmlDoc.Save("config.xml");
                XmlNodeList nodeList = xmlDoc.ChildNodes[2].ChildNodes[0].ChildNodes;
                label15.Text = nodeList[0].InnerText.ToString();
            }


It reads data from the xml document with no problems, however when it gets to the save line it gives an error saying the process cannot access the file because it is being used by another process. The file is located in my debug folder and I don't have it open. I know the node is being added because when I save to the console I can see the updated xml text. Any help will be greatly appreciated.
Posted

1 solution

Do you have any code that's called earlier to this where you open the config file or write to it? Or is this code the absolute first time that you are accessing the config file? If the former, then perhaps a file-stream is still open.
 
Share this answer
 
Comments
Neil Cross 1-Nov-10 9:44am    
That is the absolute first time I do anything to do with the config file. I execute the code in a button press if that would make any difference to how it runs.
Neil Cross 1-Nov-10 9:59am    
I solved my own problem I had to close the XmlTextReader before I tried saving. I appreciate you trying to help me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900