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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM