I have defined a config section in my app.config in the following way:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="RegisterCompanies"
type="ConfigTest.RegisterCompaniesConfig, ConfigTest"
allowLocation="true"
allowDefinition="Everywhere"/>
</configSections>
<RegisterCompanies>
<Companies>
<Company name="Tata Motors" code="Tata"/>
<Company name="Honda Motors" code="Honda"/>
</Companies>
</RegisterCompanies>
</configuration>
To read this information i have created three classes in such way :RegisterCompaniesConfig class
public class RegisterCompaniesConfig : ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
string path = Path.Combine(Application.StartupPath, "ConfigTest.exe.config");
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(path);
RegisterCompaniesConfig serviceSection = ConfigurationManager.GetSection("RegisterCompanies") as RegisterCompaniesConfig;
return serviceSection;
//return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies");
}
[System.Configuration.ConfigurationProperty("Companies")]
public Companies Companies
{
get
{
object o = this["Companies"]; return o as Companies;
}
}
}
then Companies class:
public class Companies : ConfigurationElementCollection
{
[System.Configuration.ConfigurationProperty("Company")]
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company;
}
set
{
if (base.BaseGet(index) != null)
{ base.BaseRemoveAt(index); } this.BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and the last one is Company class:
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
after that when i want to acess the section by calling following method
var config = RegisterCompaniesConfig.GetConfig();
i get the error :Configuration system failed to initialize Please anyone have a look on this above code , where is the problem , it's looking everything is fine for me....