Use variables from the web config C# Visual Studio

We create a helper class to use. This will return a variable that is set to the correct type. Credits to Steam Webhosting!

 public static class AppSettingsHelper
    {
        public static T GetValue<T>(string key, T defaultValue)
        {
            var value = ConfigurationManager.AppSettings[key];

            if (string.IsNullOrEmpty(value))
                return defaultValue;

            return (T)Convert.ChangeType(value, typeof(T));
        }
    }

We use the helper function to get the value and set the types of the variables.

        // debug / test settings
        static readonly bool testmode       = AppSettingsHelper.GetValue<bool>("TestMode", false); // toggle test mode
        static readonly bool disableupload  = AppSettingsHelper.GetValue<bool>("DisableUpload", false); // disables the upload to server if true

        // sftp settings
        static readonly int port            = AppSettingsHelper.GetValue<int>("SFTPPort", 22);
        static readonly string host         = AppSettingsHelper.GetValue<string>("SFTPHost", "feeds.dwdenney.com");

Leave a Reply