3步在config文件中建立自定义section
自定义config的作用主要是增强config的可读性,容易管理,直接进入正题
先来比较一下
使用AppSettings:使用custom section:
下面是创建过程
Step1 建立自定义class
using System; using System.Configuration; public class BlogSettings : ConfigurationSection { private static BlogSettings settings = ConfigurationManager.GetSection("BlogSettings") as BlogSettings; public static BlogSettings Settings { get { return settings; } } [ConfigurationProperty("frontPagePostCount" , DefaultValue = 20 , IsRequired = false)] [IntegerValidator(MinValue = 1 , MaxValue = 100)] public int FrontPagePostCount { get { return (int)this["frontPagePostCount"]; } set { this["frontPagePostCount"] = value; } } [ConfigurationProperty("title" , IsRequired = true)] [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\" , MinLength = 1 , MaxLength = 256)] public string Title { get { return (string)this["title"]; } set { this["title"] = value; } } }注意其中的BlogSettings不是必须的
Step2 在app.config或者web.config里面注册新的section
下面这段xml代码不知道为啥用了syntaxhighlighter贴上就乱码<configuration>
<configSections>
<section name="BlogSettings" type="Fully.Qualified.TypeName.BlogSettings, AssemblyName" />
</configSections>
<BlogSettings
frontPagePostCount="10"
title="You’ve Been Haacked" />
</configuration>
<configSections>
<section name="BlogSettings" type="Fully.Qualified.TypeName.BlogSettings, AssemblyName" />
</configSections>
<BlogSettings
frontPagePostCount="10"
title="You’ve Been Haacked" />
</configuration>
Step3 享受你的成果
string title = BlogSettings.Settings.Title; Response.Write(title); //it works!!!
如果想打破沙锅问到底的话,请参考:Unraveling the Mysteries of .NET 2.0 Configuration
代码出处:http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx