How to check if an appSettings key exists?

2019-01-21 11:39发布

How do I check to see if an Application Setting is available?

i.e. app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="someKey" value="someValue"/>
  </appSettings>
</configuration>

and in the codefile

if (ConfigurationManager.AppSettings.ContainsKey("someKey"))
{
  // Do Something
}else{
  // Do Something Else
}

7条回答
forever°为你锁心
2楼-- · 2019-01-21 12:20

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
}
查看更多
Fickle 薄情
3楼-- · 2019-01-21 12:20

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..
}
查看更多
贪生不怕死
4楼-- · 2019-01-21 12:21

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);
查看更多
看我几分像从前
5楼-- · 2019-01-21 12:25

I think the LINQ expression may be best:

   const string MyKey = "myKey"

   if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
          {
              // Key exists
          }
查看更多
Fickle 薄情
6楼-- · 2019-01-21 12:33

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

查看更多
可以哭但决不认输i
7楼-- · 2019-01-21 12:37
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
    // Key exists
}
else
{
    // Key doesn't exist
}
查看更多
登录 后发表回答