Skip to content

Instantly share code, notes, and snippets.

@sandrinodimattia
Created July 23, 2012 05:44
Show Gist options
  • Save sandrinodimattia/3162127 to your computer and use it in GitHub Desktop.
Save sandrinodimattia/3162127 to your computer and use it in GitHub Desktop.
ConfigurationProviderBase
public abstract class ConfigurationProviderBase<TSection, TException>
where TSection : ConfigurationSection
where TException : Exception, new()
{
/// <summary>
/// Name of the section to read from the app.config.
/// </summary>
private string sectionName;
/// <summary>
/// Config object used to read a custom configuration file.
/// If not set the default file will be used.
/// </summary>
private System.Configuration.Configuration config;
/// <summary>
/// Initialize the provider.
/// </summary>
/// <param name="sectionName"></param>
public ConfigurationProviderBase(string sectionName)
{
this.sectionName = sectionName;
}
/// <summary>
/// Set a custom configuration file.
/// </summary>
/// <param name="config"></param>
public void SetConfigurationFile(string file)
{
// Create the mapping.
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = file;
// Open the configuration.
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
}
/// <summary>
/// Read the configuration file.
/// </summary>
/// <returns></returns>
protected TSection Read()
{
// Try to read the config section.
TSection section = GetSection() as TSection;
if (section == null)
throw new TException();
// Done.
return section;
}
/// <summary>
/// Get the section from the default configuration file or from the custom one.
/// </summary>
/// <returns></returns>
private object GetSection()
{
if (config != null)
return config.GetSection(sectionName);
else
return ConfigurationManager.GetSection(sectionName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment