Thursday, September 24, 2015

How to read and write appSetting

To read and write appSetting vlaue on configuration file in c# we can use below simple two methord
private const string Prefix = "config";
public static T GetValue(string key, string prefix = Prefix)
    var entry = string.Format("{0}:{1}", prefix, key);
    if (entry.IsNullOrWhiteSpace())
        return default(T);
    var value = ConfigurationManager.AppSettings[entry];
    if (value.IsNullOrWhiteSpace())
        return default(T);
    if (typeof (T).IsEnum)
        return (T) Enum.Parse(typeof (T), value, true);
    if (typeof (T) == typeof (bool) && value.Is())
        return (T) Convert.ChangeType(value.As(), typeof (T));
    return (T) Convert.ChangeType(value, typeof (T));
public static T SetValue(string key, string value)
    var entry = string.Format("{0}:{1}", Prefix, key);
    var config = WebConfigurationManager.OpenWebConfiguration("~");
    config.AppSettings.Settings[entry].Value = value;
    return default(T);
so thanks to generic implementation you get the values with their data type
bool isMobile = GetValue<bool>("IsMobile");