Created
July 23, 2012 05:44
-
-
Save sandrinodimattia/3162127 to your computer and use it in GitHub Desktop.
ConfigurationProviderBase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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