[.NET] : 自订Configuration区段的未定义Attribute读写
前言 :
我们在撰写自订 Configuration时,会先定义好对应的自订 ConfigurationSection 与 Config档让程序知道该如何颇析数据。
public class SampleSection : ConfigurationSection
{
[ConfigurationProperty("propertyA")]
public string PropertyA
{
get
{
return (string)base["propertyA"];
}
set
{
base["propertyA"] = value;
}
}
[ConfigurationProperty("propertyCollectionB")]
public NameValueConfigurationCollection PropertyCollectionB
{
get
{
return (NameValueConfigurationCollection)base["propertyCollectionB"];
}
}
}
但是当我们的 Config档为下列XML,其中 propertyC的 Attribute是不固定数量与名称的时候。
上列的实践方法无法满足这样的需求。
本篇文章描述,如何使用程序来完成这样的需求。
注意 :
在 Microsoft Visual Studio IDE调试环境下,执行程序写入.config时。
程序写入的将会是*.vshost.exe.config,而不是预期中的 *.exe.config。
并且程序执行结束之后,IDE会覆盖*.vshost.exe.config成为写入前的状态。
因此会误认为程序执行失败。
只要编译完毕之后,
点选bin目录底下的*.exe,再去检查*.exe.config,就可以看到预期中的结果。
相关数据 :
[ASP.NET]撰写自己的 Configuration 区段 Part 1 : http://www.dotblogs.com.tw/regionbbs/archive/2009/05/08/custom_configuration_section_in_web_config.aspx
[ASP.NET]撰写自己的 Configuration 区段 Part 2 : http://www.dotblogs.com.tw/regionbbs/archive/2009/09/17/orgainzeyoursectionintogroupforconfiguration.aspx
[ASP.NET]撰写自己的 Configuration 区段 Part 3 : http://www.dotblogs.com.tw/regionbbs/archive/2009/10/09/customconfigurationelementcollection.aspx
[.NET] : 自订Configuration区段的数据写入 : http://www.dotblogs.com.tw/clark/archive/2010/12/23/20338.aspx
实践 :
文件下载 : Clk.ConfigurationSample2.zip
项目加入或引用 UnrecognizedAttributeConfigurationElement、UnrecognizedAttributeDictionary
自订ConfigurationSection
设定.Config
写入程序
执行结果
后记 :
自订Configuration区段,使用UnrecognizedAttributeConfigurationElement、UnrecognizedAttributeDictionary。
来做未定义的Attribute读取跟写入,其实蛮方便的 :D。
期许自己
能以更简洁的文字与程序,传达出程序设计背后的精神。
真正做到“以形写神”的境界。
原文:大专栏 [.NET] 自订Configuration区段的未定义Attribute读写