erstellen Configuration Firma:
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;
}
}
}
Configuration:
public class Companies
: ConfigurationElementCollection
{
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);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
und Configuration:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
und Sie müssen auch Ihre neue Konfiguration Abschnitt in web.config (App registrieren. Konfig):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
dann laden Sie Ihre Konfiguration mit
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
Seine erwähnenswert, dass, wenn Sie eine MVC-App verwenden, dann aufgelistet der Abschnitt in Ordnung ist. Bei einer Konsolen-App, einem Web-Service und vielleicht anderen müssen Sie ', AssemblyName' hinter 'blablabla.RegisterCompaniesConfig' haben. – KevinDeus
Muss die Assembly im type-Attribut des Abschnitts-Tags angeben. – ilmatte
Ich bekomme die Ausnahme "nicht erben von 'System.Configuration.IConfigurationSectionHandler ".. was mache ich falsch? – Oysio