使用Linq to XML 修改app.config

使用其他的方法修改app.config无效。而且修改的是*.vshost.exe.Config,程序运行时正常,关闭之后就还是原来的值。

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
             configuration.AppSettings.Settings["节点名称"].Value ="0";  
             configuration.Save(ConfigurationSaveMode.Modified);   
其他方法(测试无效)

直接上代码。

 //获取config路径
                string path = System.Windows.Forms.Application.ExecutablePath + ".config";
                XDocument doc = XDocument.Load(path);
                //查找所有节点
                IEnumerable<XElement> element = doc.Element("configuration").Element("appSettings").Elements();
                //遍历节点
                foreach (XElement item in element)
                {
                    if (item.Attribute("key") != null && item.Attribute("key").Value == "节点名称")
                    {
                        if (item.Attribute("value") != null)
                        {
                            item.Attribute("value").SetValue(DateTime.Now.ToString("d"));
                        }
                    }
                }
                //保存
                doc.Save(path);

 

posted @ 2014-02-24 10:02  xiaocong_soft  阅读(697)  评论(0编辑  收藏  举报