2024年3月26日发(作者:)

一步一步教你玩转.NET Framework的配置文件

在一般的项目中,为了使你的代码更加灵活,更方便调整,减少不必要的hard code,我们都

在config中添加许多配置信息,一般可以选择.NET自带的配置文件形式或者web

项目中的来完成配置工作。

.NET中提供了几个和配置有关的类来支持用完轻松的完成配置文件的读写设置:

urationSectionGroup

一般和你项目中使用的Assambly保持1:1的对应关系,这样划分使得结构相对清晰,权责

明确。当然你可以不使用它,这样一旦你的Assambly在别的地方要被重用时,找出相应的

config信息就变得很困难。

urationSection

维护一个相对独立的配置节,使用时需现在节点下声

明。我们熟悉的以及

就是.NET为我们预留的一个Section。

urationElementCollection &

urationElement

就是Section下具体的配置信息和配置信息的集合了。

下面来看看怎么使用这些类玩转

1.初级玩法

最初级的用法当然是使用,我们在 中添加

MyConfigString

"

value

="

Test Config Data

"/>

访问它

public

class

AppSettingConfig

{

public

string

resultValue;

public

AppSettingConfig()

{

this

.resultValue =

tings["

MyConfigString

"].ToString();

}

}

[TestMethod]

public

void

TestAppSettingConfigNode()

{

AppSettingConfig appCon =

new

AppSettingConfig();

al("

Test Config Data

", Value);

}

没有问题!

我们加个Section来看看如何访问:

MySectionGroup

">

MyFirstSection

"

type="

narySectionHandler

"/>

MySecondSection

"

type="

narySectionHandler

"/>

First

"

value

="

First Section

"/>

Second

"

value

="

Second Section

"/>

注意我们在section的type中给出了

narySectionHandler,这也限制了我们在具体的

ConfigurationElement中只能使用的形式,使得我们GetSection()

方法返回的是一个IDictory对象,我们可以根据Key来取得相应的值

public

class

SectionConfig

{

public

string

resultValue;

public

SectionConfig()

{

uration config =

eConfiguration(

);

IDictionary dic =

tion("

MySectionGroup/MySecondSection

")

as

IDictionary;

this

.resultValue = dic["

Second

"].ToString();

}

}

[TestMethod]