.NET读取指定Config配置文件和自定义节点

.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实现,



  
    

 

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");

源码下载

你可能感兴趣的:(.NET)