生活随笔
收集整理的這篇文章主要介紹了
C# 动态获取、修改、更新配置文件 实现思路
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
???????
? ? ? ?1、添加System.Configuration.dll引用;程序中添加using System.Configuration;
? ? ? ?讀取數據:(tbHost為文本控件)
[csharp] view plain copy print? tbHost.Text?=?ConfigurationManager.AppSettings["host"].ToString();?? tbHost.Text = ConfigurationManager.AppSettings["host"].ToString(); ? ? ? ?2、修改、更新數據
[csharp] view plain copy print? private?void?btnOk_Click(object?sender,?EventArgs?e)??????????{??????????????if?(tbHost.Text.Trim().Equals("")?||?tbUserid.Text.Trim().Equals(""))?return;??????????????????????????????UpdateConfig("host",?tbHost.Text.Trim());??????????????UpdateConfig("userid",?tbUserid.Text.Trim());??????????}????????????private?void?UpdateConfig(string?key,string?value)??????????{??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????Configuration?config?=?ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);??????????????config.AppSettings.Settings[key].Value?=?value;??????????????config.Save(ConfigurationSaveMode.Full);??????????????ConfigurationManager.RefreshSection("appSettings");??????????}?? private void btnOk_Click(object sender, EventArgs e){if (tbHost.Text.Trim().Equals("") || tbUserid.Text.Trim().Equals("")) return;// 修改并更新配置文件UpdateConfig("host", tbHost.Text.Trim());UpdateConfig("userid", tbUserid.Text.Trim());}private void UpdateConfig(string key,string value){// 通過Xml方式(需using System.xml;)//XmlDocument doc = new XmlDocument();//doc.Load(Application.ExecutablePath + ".config");//XmlNode node = doc.SelectSingleNode(@"//add[@key='" + key + "']"); // 定位到add節點//XmlElement element = (XmlElement)node;//element.SetAttribute("value", value); // 賦值//doc.Save(Application.ExecutablePath + ".config");//ConfigurationManager.RefreshSection("appSetting"); // 刷新節點// 利用ConfigurationConfiguration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);config.AppSettings.Settings[key].Value = value;config.Save(ConfigurationSaveMode.Full);ConfigurationManager.RefreshSection("appSettings");}
? ? ? ?說明:經常遇到的問題是修改數據后配置文件未能立即生效,再次讀取時依然是修改前的數據。參考上述代碼時,如果還遇到這個問題,可嘗試把“Xml方式”(即UpdateConfig()中注釋部分取消注釋)和Congiguration方式一起使用。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的C# 动态获取、修改、更新配置文件 实现思路的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。