自定义配置文件帮助类

利用ExeConfigurationFileMap类将自定义配置文件转换为Configuration类进行数据读取

代码很简单,就不做扼要说明

 1  /// <summary>
 2     /// 自定义配置文件
 3     /// </summary>
 4     public class ConfigHelper
 5     {
 6         #region  配置属性节点
 7         private static string _test1;
 8         /// <summary>
 9         /// 获取Test1 
10         /// </summary>
11         public static string Test1
12         {
13             get
14             {
15                 if (string.IsNullOrWhiteSpace(_test1))
16                 {
17                     ConfigDataLoad();
18                 }
19                 return _test1;
20             }
21         }
22 
23 
24         private static string _test2;
25         /// <summary>
26         /// 获取Test1 
27         /// </summary>
28         public static string Test2
29         {
30             get
31             {
32                 if (string.IsNullOrWhiteSpace(_test2))
33                 {
34                     ConfigDataLoad();
35                 }
36                 return _test2;
37             }
38         }
39 
40 
41         private static string _test3;
42         /// <summary>
43         /// 获取Test1 
44         /// </summary>
45         public static string Test3
46         {
47             get
48             {
49                 if (string.IsNullOrWhiteSpace(_test3))
50                 {
51                     ConfigDataLoad();
52                 }
53                 return _test3;
54             }
55         }
56         #endregion
57 
58 
59 
60 
61         #region 初始化配置
62 
63 
64         /// <summary>
65         /// 初始化配置文件
66         /// </summary>
67         private static void ConfigDataLoad()
68         {
69             //获取文件路径
70             string fileName = AppDomain.CurrentDomain.BaseDirectory + @"Configuration\Test.config";
71             if (File.Exists(fileName))
72             {
73                 ExeConfigurationFileMap file = new ExeConfigurationFileMap
74                 {
75                     ExeConfigFilename = fileName
76                 };
77                 //将文件转换为Configuration
78                 Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
79                 SetData(config);
80             }
81             else
82             {
83                 throw new Exception("配置文件不存在");
84             }
85         }
86         /// <summary>
87         /// 初始化值
88         /// </summary>
89         private static void SetData(Configuration config)
90         {
91             _test1 = config.AppSettings.Settings["test1"].Value;
92             _test2 = config.AppSettings.Settings["test2"].Value;
93             _test3 = config.AppSettings.Settings["test3"].Value;
94         }
95         #endregion
96 
97     }

 

posted on 2018-08-02 10:38  高兴happy  阅读(1610)  评论(0编辑  收藏  举报