怎么把自己的配置文件配置到app.config中?
- 方案1:在app.config中添加
<!--应用配置-->
<appSettings configSource="Conf\AppSettings.config" />
如果我需要自己定义单独的多个配置文件,又该怎么处理才可以把配置文件添加app.config中呢?
- 方案2:定义ConfigurationSection类
MyConfigurationSection
public class MyConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("", IsDefaultCollection = true)]
public KeyValueConfigurationElementCollection My
{
get { return (KeyValueConfigurationElementCollection)base[""]; }
} public string GetValueByKey(string key)
{
foreach (KeyValueConfigurationElement item in this.My)
{
if (item.Key == key)
return item.Value;
} return string.Empty;
} //[ConfigurationProperty("configSource", IsRequired = false)]
//public string ConfigSource
//{
// get { return (string)base["configSource"]; }
// set
// {
// base["configSource"] = value;
// }
//}
}
KeyValueConfigurationElementCollection
public class KeyValueConfigurationElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new KeyValueConfigurationElement();
} protected override object GetElementKey(ConfigurationElement element)
{
return (element as KeyValueConfigurationElement).Key;
} public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
} protected override string ElementName
{
get { return "add"; }
}
}
KeyValueConfigurationElement
public class KeyValueConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("key", IsRequired = true)]
public string Key
{
get { return (string)base["key"]; }
set { base["key"] = value; }
} [ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)base["value"]; }
set { base["value"] = value; }
}
}
修改app.config配置文件:
<configSections>
<section name="my" type="DTCore.MyConfigurationSection,DTCore"/>
</configSections> <mre configSource="Conf\My_Settings.config" />
Conf\My_Settings.config
<?xml version="1.0" encoding="utf-8"?>
<my>
<add key="DT.AKey" value="c key"/>
<add key="DT.CKey.RIPPRB" value="the value"/>
</my>
怎么调用:
MyConfigurationSection mySection=(MyConfigurationSection)ConfigurationManager.GetSection("my");
string value=mySection.GetValueByKey("DT.AKey");