C#获取config文件的appSettings节点封装技巧
- 时间:2015年04月02日 15:33:59 来源:魔法猪系统重装大师官网 人气:8844
C#的开发中,无论你是winform开发还是webform开发,都需要通过config文件来配置一些信息,因此我们也经常需要获取其中的appsettings节点的值。当然,.net已经对访问这个节点做了封装,我们可以很方便的访问该节点。但是,我觉得还是不够满意,因为我需要在获取不到节点的时候能够返回默认的值,获取的时候能够自动转为我需要的类型,我需要能够随时指定config文件,而不仅仅是默认的web.config文件或者是*.exe.config文件。尤其最后的那个功能,嘿嘿,别以为这个没有用,有时候,我们是需要共用一个配置文件的。比如你在开发Windows服务的时候,你不会希望你用界面的那个程序和Windows服务的程序有两个一样的配置文件吧
直接贴代码:
1 ///
2 /// 获取AppSetting里面的内容
3 ///
4 ///
5 /// The default value.
6 /// The key.
7 ///
8 public static T GetAppSettingValue
9 {
10 string value = ConfigurationManager.AppSettings[key];
11 if (!string.IsNullOrEmpty(value))
12 {
13 try
14 {
15 defaultValue = (T)Convert.ChangeType(value, typeof(T));
16 }
17 catch
18 {
19 }
20 }
21 return defaultValue;
22 }
23
24 ///
25 /// 获取指定的Config文件的AppSetting里面的指定键值对应的value值
26 ///
27 ///
28 /// The default value.
29 /// The key.
30 /// The file.
31 ///
32 public static T GetAppSettingValue
33 {
34 var map = new ExeConfigurationFileMap
35 {
36 ExeConfigFilename = file
37 };
38 Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
39 string value = config.AppSettings.Settings[key].Value;
40
41 if (!string.IsNullOrEmpty(value))
42 {
43 try
44 {
45 defaultValue = (T)Convert.ChangeType(value, typeof(T));
46 }
47 catch
48 {
49 }
50 }
51 return defaultValue;
52 }





