您的位置:首页 > 编程语言 > C#

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

2016-06-16 00:02 555 查看
       

       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"); // 刷新节点

// 利用Configuration
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("appSettings");
}

       说明:经常遇到的问题是修改数据后配置文件未能立即生效,再次读取时依然是修改前的数据。参考上述代码时,如果还遇到这个问题,可尝试把“Xml方式”(即UpdateConfig()中注释部分取消注释)和Congiguration方式一起使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息