Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save sandcastle/07a09aeffe71a60a898c to your computer and use it in GitHub Desktop.

Select an option

Save sandcastle/07a09aeffe71a60a898c to your computer and use it in GitHub Desktop.
Helper methods for reading app.config values.
/// <summary>
/// Helper methods for reading configuration values.
/// </summary>
public static class ConfigurationHelpers
{
/// <summary>
/// Reads an enum value from configutation.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <param name="key">The configuration key.</param>
/// <exception cref="ArgumentException">Thrown when the type is not an enum.</exception>
/// <exception cref="ConfigurationErrorsException">Thrown when the key is not found or the value is invalid.</exception>
/// <returns>The enum value.</returns>
public static T ReadEnumFromConfig<T>(string key) where T : struct, IConvertible
{
if (typeof(T).IsEnum == false)
{
throw new ArgumentException("T must be an enumerated type");
}
T result;
var value = ConfigurationManager.AppSettings[key];
if (String.IsNullOrEmpty(value) || Enum.TryParse(value, true, out result) == false)
{
throw new ConfigurationErrorsException(String.Format("The configuration key '{0}' was not found or its value is invalid.", key));
}
return result;
}
/// <summary>
/// Reads a Uri value from configuration.
/// </summary>
/// <param name="key">The configuration key.</param>
/// <param name="kind">The <see cref="UriKind"/>.</param>
/// <exception cref="ConfigurationErrorsException">Thrown when the key is not found or the value is invalid.</exception>
/// <returns>The Uri value.</returns>
public static Uri ReadUriFromConfig(string key, UriKind kind = UriKind.Absolute)
{
Uri result;
var value = ConfigurationManager.AppSettings[key];
if (String.IsNullOrEmpty(value) || Uri.TryCreate(value, kind, out result) == false)
{
throw new ConfigurationErrorsException(String.Format("The configuration key '{0}' was not found or its value is invalid.", key));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment