(转)c# 配置文件之configSections配置
https://www.cnblogs.com/caoyc/p/5999720.html
对于小型项目来说,配置信息可以通过appSettings进行配置,而如果配置信息太多,appSettings显得有些乱,而且在开发人员调用时,也不够友好,节点名称很容易写错,这时,我们有几种解决方案
1 自己开发一个配置信息持久化类,用来管理配置信息,并提供面向对象的支持2 使用.net自带的configSections,将配置信息分块管理,并提供实体类,便于开发人员友好的去使用它本文主要说说第二种方案,它由实体类,实体类工厂及配置文件三个部分,看代码:
实体类设计:
1 namespace Configer
2 {
3 /// <summary>
4 /// 网站信息配置节点
5 /// </summary>
6 public class WebConfigSection : ConfigurationSection
7 {
8 /// <summary>
9 /// 网站名称
10 /// </summary>
11 [ConfigurationProperty("WebName", DefaultValue = "", IsRequired = true, IsKey = false)]
12 public string WebName
13 {
14
15 get { return (string)this["WebName"]; }
16 set { this["WebName"] = value; }
17 }
18 /// <summary>
19 /// 网站域名
20 /// </summary>
21 [ConfigurationProperty("DoMain", DefaultValue = "", IsRequired = true, IsKey = false)]
22 public string DoMain
23 {
24
25 get { return (string)this["DoMain"]; }
26 set { this["DoMain"] = value; }
27 }
28
29 }
30 }
实体工厂类设计,主要用来生产实体配置信息
1 namespace Configer
2 {
3 /// <summary>
4 /// 网站配置信息工厂
5 /// </summary>
6 public class WebConfigManager
7 {
8 /// <summary>
9 /// 配置信息实体
10 /// </summary>
11 public static readonly WebConfigSection Instance = GetSection();
12
13 private static WebConfigSection GetSection()
14 {
15 WebConfigSection config = ConfigurationManager.GetSection("WebConfigSection") as WebConfigSection;
16 if (config == null)
17 throw new ConfigurationErrorsException();
18 return config;
19 }
20 }
21 }
而最后就是.config文件了,它有configSections和指定的sections块组成,需要注意的是configSections必须位于configuration的第一个位置
1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3 <configSections> 4 <section name="WebConfigSection" type="Configer.WebConfigSection, test"/> 5 </configSections> 6 <connectionStrings> 7 <add name="backgroundEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\sqlexpress;Initial Catalog=background;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /> 8 </connectionStrings> 9 10 <WebConfigSection WebName="占占网站" DoMain="www.zhanzhan.com" /> 11 <appSettings> 12 <add key="site" value="www.zzl.com"/> 13 14 </appSettings> 15 </configuration>
以上三步实现后,我们就可以调用了,呵呵
1 static void Main(string[] args)
2 {
3 Console.WriteLine(System.Configuration.ConfigurationManager.AppSettings["site"]);
4 Console.WriteLine(WebConfigManager.Instance.DoMain);
5 Console.WriteLine(WebConfigManager.Instance.WebName);
6 }

浙公网安备 33010602011771号