更新Xml文件 [英] Updating a Xml file

查看:106
本文介绍了更新Xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未使用过配置文件,但是现在我需要快速学习,所以如果我犯了明显的错误或提出了愚蠢的问题,请耐心等待.我尝试将新节点添加到配置文件,并使用以下代码对它们的值进行硬编码;

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



它可以毫无问题地从xml文档中读取数据,但是,当它到达保存行时,会出现错误,指出该进程无法访问该文件,因为该文件正在被另一个进程使用.该文件位于我的调试文件夹中,但我没有打开它.我知道要添加该节点,因为当我保存到控制台时,我可以看到更新的xml文本.任何帮助将不胜感激.



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.

推荐答案

在打开配置文件或写入配置文件之前,您是否有调用此代码的任何代码?还是此代码绝对是您首次访问配置文件?如果是前者,那么也许文件流仍处于打开状态.
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.


这篇关于更新Xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆