轻量级Config文件AppSettings节点编辑帮助类

2018-12-27 07:43:23来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

 1 using System.Configuration;
 2 using System.Windows.Forms;
 3 
 4 namespace Allyn.Common
 5 {
 6     public class XmlHeper
 7     {
 8         ///<summary> 
 9         ///返回Config文件中appSettings配置节的value项  
10         ///</summary> 
11         ///<param name="strKey">节点Key</param> 
12         ///<returns></returns> 
13         public static string GetAppConfig(string strKey)
14         {
15             string file = Application.ExecutablePath;
16             Configuration config = ConfigurationManager.OpenExeConfiguration(file);
17 
18             foreach (string key in config.AppSettings.Settings.AllKeys)
19             {
20                 if (key == strKey)
21                 {
22                     return config.AppSettings.Settings[strKey].Value.ToString();
23                 }
24             }
25             return string.Empty;
26         }
27 
28         ///<summary>  
29         ///在Config文件中appSettings配置节增加一对键值对  
30         ///</summary>  
31         ///<param name="newKey">节点名称</param>  
32         ///<param name="newValue">信值</param>  
33         public static void UpdateAppConfig(string newKey, string newValue)
34         {
35             string file = System.Windows.Forms.Application.ExecutablePath;
36             Configuration config = ConfigurationManager.OpenExeConfiguration(file);
37 
38             bool exist = false;
39 
40             foreach (string key in config.AppSettings.Settings.AllKeys)
41             {
42                 if (key == newKey) {  exist = true; }
43             }
44 
45             if (exist)  { config.AppSettings.Settings.Remove(newKey); }
46 
47             config.AppSettings.Settings.Add(newKey, newValue);
48             config.Save(ConfigurationSaveMode.Modified);
49 
50             ConfigurationManager.RefreshSection("appSettings");
51         }
52     }
53 }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:SignalR2简易数据看板演示

下一篇:一不小心发现了个Asp.Net Bug