Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an appSettings key exists?

People also ask

Where is appSettings in web config?

AppSetting element section exists under the Configuration tag. All custom settings o a web application can be stored here.

Where is app config C#?

A: When you compile an application, its app. config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a "text.exe. config" in your bin directory.

Why appSettings keys in web config are not case sensitive?

Why appsettings keys (in web. config) are not case sensitive ? The default comparer is a CaseInsensitiveComparer that uses the conventions of the invariant culture; that is, key comparisons are case-insensitive by default.

What is the appSettings section in the web config file?

AppSetting section in the configuration file is a section that allows us to keep configurable and application wide settings (for e.g.: ConnectionString) that an application requires in order to perform the tasks properly. This helps in easy maintenance and deployment of the application.


MSDN: Configuration Manager.AppSettings

if (ConfigurationManager.AppSettings[name] != null)
{
// Now do your magic..
}

or

string s = ConfigurationManager.AppSettings["myKey"];
if (!String.IsNullOrEmpty(s))
{
    // Key exists
}
else
{
    // Key doesn't exist
}

if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
    // Key exists
}
else
{
    // Key doesn't exist
}

Safely returned default value via generics and LINQ.

public T ReadAppSetting<T>(string searchKey, T defaultValue, StringComparison compare = StringComparison.Ordinal)
{
    if (ConfigurationManager.AppSettings.AllKeys.Any(key => string.Compare(key, searchKey, compare) == 0)) {
        try
        { // see if it can be converted.
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter != null) defaultValue = (T)converter.ConvertFromString(ConfigurationManager.AppSettings.GetValues(searchKey).First());
        }
        catch { } // nothing to do just return the defaultValue
    }
    return defaultValue;
}

Used as follows:

string LogFileName = ReadAppSetting("LogFile","LogFile");
double DefaultWidth = ReadAppSetting("Width",1280.0);
double DefaultHeight = ReadAppSetting("Height",1024.0);
Color DefaultColor = ReadAppSetting("Color",Colors.Black);

var isAlaCarte = 
    ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") && 
    bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));

If the key you are looking for isn't present in the config file, you won't be able to convert it to a string with .ToString() because the value will be null and you'll get an "Object reference not set to an instance of an object" error. It's best to first see if the value exists before trying to get the string representation.

if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["myKey"]))
{
    String myKey = ConfigurationManager.AppSettings["myKey"].ToString();
}

Or, as Code Monkey suggested:

if (ConfigurationSettings.AppSettings["myKey"] != null)
{
// Now do your magic..
}

Upper options gives flexible to all manner, if you know key type try parsing them bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);


I think the LINQ expression may be best:

   const string MyKey = "myKey"

   if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
          {
              // Key exists
          }