AppSettingManager

 1     public class AppSettingManager
 2     {
 3         public static bool Update(string key, string value)
 4         {
 5 
 6             try
 7             {
 8                 var config = Create();
 9                 if (config == null)
10                 {
11                     return false;
12                 }
13                 var isModified = !string.IsNullOrEmpty(Get(key));
14                 if (isModified)
15                 {
16                     config.AppSettings.Settings.Remove(key);
17                 }
18                 // Add an Application Setting.
19                 config.AppSettings.Settings.Add(key, value);
20                 // Save the changes in App.config file.
21                 config.Save(ConfigurationSaveMode.Modified);
22                 // Force a reload of a changed section.
23                 ConfigurationManager.RefreshSection("appSettings");
24                 return true;
25             }
26             catch (Exception)
27             {
28                 return false;
29             }
30 
31         }
32 
33         public static bool Add(string key, string value)
34         {
35             try
36             {
37                 var config = Create();
38                 if (config == null)
39                 {
40                     return false;
41                 }
42                 config.AppSettings.Settings.Add(key, value);
43                 config.Save(ConfigurationSaveMode.Modified);
44                 ConfigurationManager.RefreshSection("appSettings");
45                 return true;
46             }
47             catch (Exception)
48             {
49                 return false;
50 
51             }
52 
53         }
54 
55         public static string Get(string key)
56         {
57             var config = Create();
58             if (config == null)
59             {
60                 return null;
61             }
62             return config.AppSettings.Settings[key].Value;
63         }
64 
65         private static Configuration Create()
66         {
67             try
68             {
69                 return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
70             }
71             catch (Exception)
72             {
73                 return null;
74             }
75         }
76     }

 

posted @ 2014-07-28 12:00  b̶i̶n̶g̶.̶  阅读(261)  评论(0编辑  收藏  举报