ASP.NET C# Web.Config helper class

Posted on April 5, 2014 by Michael Roma

The following is a C# helper class that reads App Settings in your ASP.NET Web.config file.

// add this include
using System.Configuration;

namespace roma
{
    public static class Config
    {
        // example setting
        // numeric example   
        public static double CacheMinutes { get { return Get("roma.CacheMinutes"); } }
        
        // boolean example
        public static bool IsTestMode { get { return Get("roma.IsTestMode"); } }
        
        // email addresses
        public static string DefaultEmailTo { get { return Get("roma.DefaultEmailTo"); } }
        
        // constant contact
        public static string ConstantContactAPIKey { get { return Get("roma.ConstantContact.APIKey"); } }
        public static string ConstantContactAccessToken { get { return Get("roma.ConstantContact.AccessToken"); } }
        public static string ConstantContactEmailList { get { return Get("roma.ConstantContact.EmailList"); } }

        // sales force
        public static string SalesForceOID { get { return Get("roma.SalesForce.OID"); } }
        public static string SalesForceWebToLeadURL { get { return Get("roma.SalesForce.WebToLeadURL"); } }        


        // helper to extract a web config value
        private static T Get(string key)
        {
            // try to convert
            try
            {
                return (T)Convert.ChangeType(ConfigurationManager.AppSettings[key], typeof(T));
            }
            catch (Exception) { }

            // return default
            return default(T);
        }
    }
}
comments powered by Disqus