C#中动态读写App.config配置文件
2024-10-18 22:35:15
转自:http://blog.csdn.net/taoyinzhou/article/details/1906996
app.config 修改后,如果使用cofnigurationManager立即读取,不能获取修改后的值,只能获取缓存中的原值。使用下面直接操场xml文件的方式可以动态读写配置文件。
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; namespace TaoNet.Common.TaoCommon { /// <summary> /// C#中动态读写App.config配置文件 /// </summary> public class AppConfig { public AppConfig() { /// /// TODO: 在此处添加构造函数逻辑 /// } /// <summary> /// 写操作 /// </summary> /// <param name="strExecutablePath"></param> /// <param name="AppKey"></param> /// <param name="AppValue"></param> public static void ConfigSetValue(string strExecutablePath,string AppKey, string AppValue) { XmlDocument xDoc = new XmlDocument(); //获取可执行文件的路径和名称 xDoc.Load(strExecutablePath + ".config"); XmlNode xNode; XmlElement xElem1; XmlElement xElem2; xNode = xDoc.SelectSingleNode("//connectionStrings"); // xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@name='" + AppKey + "']"); if (xElem1 != null) xElem1.SetAttribute("connectionString", AppValue); else { xElem2 = xDoc.CreateElement("add"); xElem2.SetAttribute("name", AppKey); xElem2.SetAttribute("connectionString", AppValue); xNode.AppendChild(xElem2); } xDoc.Save(strExecutablePath + ".config"); } /// <summary> /// 读操作 /// </summary> /// <param name="strExecutablePath"></param> /// <param name="appKey"></param> /// <returns></returns> public string ConfigGetValue(string strExecutablePath, string appKey) { XmlDocument xDoc = new XmlDocument(); try { xDoc.Load(strExecutablePath + ".config"); XmlNode xNode; XmlElement xElem; xNode = xDoc.SelectSingleNode("//appSettings"); xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']"); if (xElem != null) return xElem.GetAttribute("value"); else return ""; } catch (Exception) { return ""; } } } }
最新文章
- (转)python requests的安装与简单运用
- 注释声明:TODO HACK XXX FIXME REVIEW
- zend create project prepare
- Java命令
- am335x UART1输入u-boot 调试信息代码修改
- PHP如何实现文件上传
- linux 启动模式
- xtjh
- gridview--基本的gridview
- android Loger日志类(获取内置sd卡)
- Java权限讲解
- PHP获取用户访问IP地址的5种方法
- call()与apply()传参需要注意的一点
- MULE-ET0 、 ET1、ET2、PT1、PT2
- CCNA网络工程师学习进程(9)GNS3的安装与配置
- input输入框控制字数
- 解决ASP.NET MVC 检测到有潜在危险的 Request.Form 值
- CPU火焰图
- leetcode 编译问题:Line x: member access within null pointer of type &#39;struct TreeNode&#39;
- python全栈开发笔记---------数据类型****整理****
热门文章
- 前端开发流程之(线上)绝对地址(图片+css+js)
- Java线程中yield与join方法的区别
- http://stackoverflow.com/questions/6065169/requestanimationframe-with-this-keyword
- 【转】CentOS 6.5安装pyspider过程记录
- linux下使用shell查看apache IP访问量
- WCF初探-7:WCF服务配置工具使用
- Codeforces 451E Devu and Flowers(组合计数)
- Windows 通用应用尝试开发 “51单片机汇编”第二次更新总结
- [CQOI 2014] 数三角形 &; 机械排序臂
- html a 链接标签title属性换行鼠标悬停提示内容的换行效果