C#操作config文件的操作

本文提供了一个用于操作Web.config文件中AppSettings部分的实用类。该类包括获取、设置和添加配置项的方法。
1.操作Web.config文件封装的类:
ContractedBlock.gifExpandedBlockStart.gifCode
 1 public class ConfigOperation 
 2 
 3 static Configuration config; 
 4 static ConfigOperation() 
 5 
 6 
 7 
 8 static Configuration GetConfig() 
 9 
10 if (config == null
11 
12 config = WebConfigurationManager.OpenWebConfiguration("~"); 
13 
14 return config; 
15 
16 private static bool IsAppSettingsExistKey(string key) 
17 
18 
19 Configuration config = GetConfig(); 
20 foreach (string str in config.AppSettings.Settings.AllKeys) 
21 
22 if (str == key) 
23 
24 return true
25 
26 
27 return false ; 
28 
29 public static string GetValueByKey(string key) 
30 
31 if (IsAppSettingsExistKey(key)) 
32 
33 Configuration config = GetConfig(); 
34 return config.AppSettings.Settings[key].Value; 
35 
36 return "none"
37 
38 public static bool SetValuebyKey(string key, string value) 
39 
40 if (IsAppSettingsExistKey(key)) 
41 
42 Configuration config = GetConfig(); 
43 config.AppSettings.Settings[key].Value = value; 
44 config.Save(ConfigurationSaveMode.Modified); 
45 return true
46 
47 else 
48 
49 return false
50 
51 
52 public static bool AddAppSetting(string key, string value) 
53 
54 bool issucceed = false
55 try 
56 
57 if (IsAppSettingsExistKey(key)) 
58 
59 SetValuebyKey(key, value); 
60 issucceed = true
61 
62 
63 else 
64 
65 Configuration config = GetConfig(); 
66 config.AppSettings.Settings.Add(key, value); 
67 config.Save(ConfigurationSaveMode.Modified); 
68 issucceed = true
69 
70 
71 catch 
72 
73 issucceed = false
74 
75 return issucceed; 
76 
77 }
78 

转载于:https://www.cnblogs.com/dotneter/archive/2009/06/04/1496040.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值