当前位置: 代码迷 >> 综合 >> C# 动态获取、修改、更新配置文件 实现思路
  详细解决方案

C# 动态获取、修改、更新配置文件 实现思路

热度:63   发布时间:2024-01-16 01:21:29.0



       

       1、添加System.Configuration.dll引用;程序中添加using System.Configuration;

       读取数据:(tbHost为文本控件)

tbHost.Text = ConfigurationManager.AppSettings["host"].ToString();

       2、修改、更新数据

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方式一起使用。