Thursday, December 02, 2010

eigene config klasse

muss von ConfigurationSection abgeleitet sein, braucht eine Property SectionName, anbei der Code zum lesen und Schreiben, bei Fehlersuche ist es ratsam im Visual Studio unter Debug/Exceptions bei CLR Exceptions das Häckchen bei Thrown anzuhacken, da Fehler sonst vom Configurationmanager unterdrückt werden. Aktiviert man aber dass die Ausführung bei thrown Exceptions unterbricht,bekommt man die Orignal Fehlermeldung des Configurationmanagers.


private string _SectionName;
public string Name
{
get
{
return this.SectionInformation.Name;
}
}
public string SectionName
{
get
{
return _SectionName;
}
set
{
_SectionName = value;
}
}

public static List GetSectionsFromConfig()
{
Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup csg = c.GetSectionGroup("DataContextParams");
List ldcp = new List();
foreach (DataContextParams dcp in csg.Sections)
{
ldcp.Add(dcp);
}
return ldcp;
}

///
/// schreibt dieses Objekt in die Config
///

/// wenn null wird in die execonfig geschrieben
public void SaveSectionToConfig(string configfile)
{
ExeConfigurationFileMap oConfigFile = new ExeConfigurationFileMap();
Configuration oConfiguration;
if (null == configfile)
{
oConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
else
{
oConfigFile.ExeConfigFilename = configfile;
oConfiguration = ConfigurationManager.OpenMappedExeConfiguration(oConfigFile, ConfigurationUserLevel.None);
}

//Add it to the configuration's sections
oConfiguration.Sections.Add(SectionName, this);

//Save the given section in the configuration file
this.SectionInformation.ForceSave = true;
oConfiguration.Save(ConfigurationSaveMode.Full);

}

No comments: