读写app.config AppSettings,保留注释与不保留注释
2016-05-18 14:38
281 查看
不保留
不删注释:
using System; using System.Configuration; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ReadAllSettings(); ReadSetting("Setting1"); ReadSetting("NotValid"); AddUpdateAppSettings("NewSetting", "May 7, 2014"); AddUpdateAppSettings("Setting1", "May 8, 2014"); ReadAllSettings(); } static void ReadAllSettings() { try { var appSettings = ConfigurationManager.AppSettings; if (appSettings.Count == 0) { Console.WriteLine("AppSettings is empty."); } else { foreach (var key in appSettings.AllKeys) { Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]); } } } catch (ConfigurationErrorsException) { Console.WriteLine("Error reading app settings"); } } static void ReadSetting(string key) { try { var appSettings = ConfigurationManager.AppSettings; string result = appSettings[key] ?? "Not Found"; Console.WriteLine(result); } catch (ConfigurationErrorsException) { Console.WriteLine("Error reading app settings"); } } static void AddUpdateAppSettings(string key, string value) { try { var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var settings = configFile.AppSettings.Settings; if (settings[key] == null) { settings.Add(key, value); } else { settings[key].Value = value; } configFile.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name); } catch (ConfigurationErrorsException) { Console.WriteLine("Error writing app settings"); } } } }
不删注释:
public static void SaveAppSettingsMethod2(string key, string value) { //验证key value //To Do XmlDocument xml = new XmlDocument(); string configPath = Application.ExecutablePath + ".config"; xml.Load(configPath); XmlNodeList nodeList = xml.GetElementsByTagName("appSettings"); if (nodeList != null) { if (nodeList.Count >= 1) { XmlNode node = nodeList[0]; foreach (XmlNode item in node) { if (item.NodeType == XmlNodeType.Comment) { continue; } XmlAttribute xaKey = item.Attributes["key"]; XmlAttribute xaValue = item.Attributes["value"]; if (xaKey != null && xaValue != null && xaKey.Value.Equals(key)) { xaValue.Value = value; } } } } xml.Save(configPath); }
相关文章推荐
- Android ListView实现上拉加载更多和下拉刷新功能
- <connectionStrings> <appSettings> 读取方法
- object-c中的-和+
- android studio环境下,语音识别在多平台so文件下,导致无法识别的问题
- Android自定义实现FlowLayout
- OC转Swift工具
- 探究支付宝android客户端的动态加载
- 禁止Android 横屏竖屏切换
- Android自定义控件实战——实现仿IOS下拉刷新上拉加载 PullToRefreshLayout
- iOS-发布按钮动画(类似于闲鱼发布),弹出动画github开源
- Android.TextUtils 简单的工具类
- mac 系统开发android,真机调试解决方案(无数的坑之后吐血总结)
- iOS 获取当前媒体音量
- Android内存优化之——static使用篇(使用MAT工具进行分析)
- jQuery 滚动条插件之移动端 左右滑动不出现滚动条
- iOS 8 AutoLayout与Size Class自悟
- 更换NSURLSession后 报错 This application is modifying the autolayout engine from a background thread, whi
- iOS IPv6 最新升级攻略
- iOS Json转Model (一)
- Apple pay