winform程序读取和改写配置文件App.config元素的值
2015-11-05 11:09
246 查看
public string GetAppConfig(string key) { string value=""; XmlDocument doc = new XmlDocument(); doc.Load("config.xml"); //加载Xml文件 XmlElement rootElem = doc.DocumentElement; //获取根节点 XmlNodeList personNodes = rootElem.GetElementsByTagName("add"); //获取person子节点集合 foreach (XmlNode node in personNodes) { string strName = ((XmlElement)node).GetAttribute("key"); if (strName == key) { value = ((XmlElement)node).GetAttribute("value"); break; } } return value; }
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <!-- 连接时间--> <add key="CommandTimeout" value="300" /> </appSettings> </configuration>
写:
public static void SetValue(string AppKey, string AppValue) { System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); System.Xml.XmlNode xNode; System.Xml.XmlElement xElem1; System.Xml.XmlElement xElem2; xNode = xDoc.SelectSingleNode("//appSettings"); xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']"); if (xElem1 != null) xElem1.SetAttribute("value", AppValue); else { xElem2 = xDoc.CreateElement("add"); xElem2.SetAttribute("key", AppKey); xElem2.SetAttribute("value", AppValue); xNode.AppendChild(xElem2); } xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config"); }
相关文章推荐
- Swift学习-基础的语法
- 微信模板消息换行
- iOS 属性修饰符strong还是copy?
- Android应用开发中使用deeplink
- android权限大全
- 如何在一个没有root权限的Android设备上创建一个SOCKS代理(英文转载)
- iOS ,呼叫捕获抛出勉未知方法的障碍
- 一些比较好的宏定义
- 移动端图片格式调研
- android studio如何使用git
- Applications of Chi-Square Tests
- iOS开发中乱用hook可能导致灾难
- iOS-- 键盘next 和 点击 Btn
- iOS开发19-iOS CALayer的position和anchorPoint
- 树形目录结构 竖线+扩展+收缩 图标的实现
- leetcode-Happy Number
- IOS URL中文乱码
- android 5.0 ,zbar扫描java.lang.UnsatisfiedLinkError,找不到so文件
- android 四边border宽度不一致
- View事件分发机制学习笔记