.NET程序默认带的配置文件是app.config和web.config,我们也可以读取指定文件,通过下面代码,
public static Configuration GetConfig(string filename) {
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = System.AppDomain.CurrentDomain.BaseDirectory + @"\Configs\" + filename;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
return config;
}
我们在config文件里定义一个自定义简单集合节点,自定义节点通过configSections实现,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Children" type="System.Configuration.DictionarySectionHandler"/>
</configSections>
<Children>
<add key="老大" value="1" />
<add key="老二" value="2" />
<add key="老三" value="3" />
</Children>
</configuration>
public static object GetConfigurationValues(Configuration config, string sectionName) {
ConfigurationSection section = config.GetSection(sectionName);
string xml = section.SectionInformation.GetRawXml();
XmlDocument doc = new XmlDocument();
doc.Load(XmlReader.Create(new StringReader(xml)));
string type = section.SectionInformation.Type;
string assemblyName = typeof(IConfigurationSectionHandler).Assembly.GetName().FullName;
ObjectHandle configSectionHandlerHandle = Activator.CreateInstance(assemblyName, section.SectionInformation.Type);
if (configSectionHandlerHandle != null) {
IConfigurationSectionHandler handler = configSectionHandlerHandle.Unwrap() as IConfigurationSectionHandler;
return handler.Create(null, null, doc.DocumentElement);
}
return null;
}
调用,
Configuration config = GetConfig("test.config");
Hashtable ht = (Hashtable)GetConfigurationValues(config, "Children");