C# 动态获取、修改、更新配置文件 实现思路
2016-11-10 17:22
1921 查看
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)
{
// 通过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");
}
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方式一起使用。
相关文章推荐
- C# 动态获取、修改、更新配置文件 实现思路
- C#编程实现动态改变配置文件信息的方法
- java应用(非web应用)中log4j.properties动态修改配置文件,无需重启,就能立即生效,如何实现?
- 【C#】#103 动态修改App.config配置文件
- C# 怎么动态修改webservice的地址和端口 动态修改配置文件
- Asp.Net利用Ajax实现Fullcalendar动态获取更新events并修改日程单元格背景颜色
- c#获取或修改配置文件
- C#动态加载DLL,通过配置文件实现对程序集的即插即用
- C#修改config文件实现动态调用webservice实现问题
- Java SE 动态读取配置文件路径(配置文件数量不固定) 实现思路
- asp.net(c#)动态修改webservice的地址和端口(动态修改配置文件)
- c#获取或修改配置文件
- C#动态修改文件夹名称(FSO实现,不移动文件)
- C#读取配置文件详解 完全自定义实现动态加载dll
- C#动态修改文件夹名称(FSO实现,不移动文件)
- logback动态修改配置文件实现打印不同级别日志
- [转载]C# 动态修改配置文件
- php实现动态修改配置文件
- c# 怎么动态修改webservice的地址和端口 动态修改配置文件
- asp.net(c#)动态修改webservice的地址和端口(动态修改配置文件)