Am trying to implement a generic way for reading sections from a config file. The config file may contain 'standard' sections or 'custom' sections as below.
<configuration>
<configSections>
<section name="NoteSettings" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<appSettings>
<add key="AutoStart" value="true"/>
<add key="Font" value="Verdana"/>
</appSettings>
<NoteSettings>
<add key="Height" value="100"/>
<add key="Width" value="200"/>
</NoteSettings>
The method that I tried is as follows :
private string ReadAllSections()
{
StringBuilder configSettings = new StringBuilder();
Configuration configFile = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
foreach (ConfigurationSection section in configFile.Sections)
{
configSettings.Append(section.SectionInformation.Name);
configSettings.Append(Environment.NewLine);
if (section.GetType() == typeof(DefaultSection))
{
NameValueCollection sectionSettings = ConfigurationManager.GetSection(section.SectionInformation.Name) as NameValueCollection;
if (sectionSettings != null)
{
foreach (string key in sectionSettings)
{
configSettings.Append(key);
configSettings.Append(" : ");
configSettings.Append(sectionSettings[key]);
configSettings.Append(Environment.NewLine);
}
}
}
configSettings.Append(Environment.NewLine);
}
return configSettings.ToString();
}
Assuming that all custom sections will have only KEY-VALUE
- Is such an implementation possible? And if yes, is there a 'cleaner' and more elegant solution than this one?
- The above method also reads 'invisible' sections like mscorlib, system.diagnostics. Is this avoidable?
- System.Data.Dataset returns a dataset which could not be cast to a NameValueCollection. How can this be handled?
Corrections/suggestions welcome.
Thanks.