using System; | |
using System.Configuration; | |
namespace Util | |
{ | |
public static class Config | |
{ | |
public static string GetSetting(string key) => ConfigurationManager.AppSettings[key]; | |
public static bool HasSetting(string key) => !string.IsNullOrEmpty(GetSetting(key)); | |
public static string GetSettingOrDefault(string key, string defaultValue) => HasSetting(key) | |
? GetSetting(key) | |
: defaultValue; | |
public static bool IsTrue(string key) | |
{ | |
bool enabled; | |
return GetSetting(key) != null && bool.TryParse(GetSetting(key), out enabled) && enabled; | |
} | |
public static int GetSettingAsIntOrDefault(string key, int defaultValue) | |
{ | |
try | |
{ | |
return HasSetting(key) ? int.Parse(GetSetting(key)) : defaultValue; | |
} | |
catch (FormatException fomatException) | |
{ | |
throw new FormatException($"Invalid format for setting {key}, expected an int", fomatException); | |
} | |
} | |
public static string GetSettingOrError(string key) | |
{ | |
if (!HasSetting(key)) | |
throw new ConfigurationErrorsException($"Unable to find required config value with key {key}"); | |
return GetSetting(key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment