c# 修改exe.config文件并且及时更新

1.config文件地址:AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

 注意:如果是在调试程序中运行,此地址指代的是vhost.exe.config,需要使用Application.StartupPath + "/xxx.config"

2.修改代码:(根据xml文件打开,修改及保存)

XmlDocument doc = new XmlDocument();
            //获得配置文件的全路径  
            string strFileName = Application.StartupPath + "/xxx.config";
            doc.Load(strFileName);
            //找出名称为“add”的所有元素  
            XmlNodeList nodes = doc.GetElementsByTagName("add");
            XmlAttribute att;
            for (int i = 0; i < nodes.Count; i++)
            {
                //获得将当前元素的key属性  
                att = nodes[i].Attributes["name"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素  
                if (att != null && att.Value == strKey)
                {
                    //对目标元素中的第二个属性赋值  
                    att = nodes[i].Attributes["connectionString"];
                    att.Value = ConnenctionString;
                    break;
                }
            }
            //保存上面的修改  
            doc.Save(strFileName);

 3.修改完毕之后,重启程序才生效。为了避免,让其立即生效:

FieldInfo fieldInfo = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
            if (fieldInfo != null) fieldInfo.SetValue(null, 0);
原文地址:https://www.cnblogs.com/gaara-zhang/p/10032139.html