如何检查appSettings键是否存在?

bit*_*cle 140 c# configurationmanager appsettings

如何检查应用程序设置是否可用?

即app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="someKey" value="someValue"/>
  </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

并在代码文件中

if (ConfigurationManager.AppSettings.ContainsKey("someKey"))
{
  // Do Something
}else{
  // Do Something Else
}
Run Code Online (Sandbox Code Playgroud)

小智 213

MSDN:Configuration Manager.AppSettings

if (ConfigurationManager.AppSettings[name] != null)
{
// Now do your magic..
}
Run Code Online (Sandbox Code Playgroud)

要么

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

  • 它抛出"对象引用未设置为对象的实例" (9认同)
  • 不,这是错误的。如果应用程序设置 xml 节点中不存在“myKey”,则代码将引发异常。 (3认同)
  • 这不是最佳答案,因为这会抛出异常.Divyesh Patel是一个更好的解决方案. (3认同)
  • 我们的库中有一个类似SQL的IsNull函数(https://gist.github.com/eithe/5589891),这使得检索设置非常方便:`Dim configValue As String = Util.IsNull(ConfigurationManager.AppSettings.获取("SettingName"),String.Empty)` (2认同)
  • 如果您检查 IsNullOrEmpty,那么当您实际拥有一个带有空字符串值的键作为有效设置时,您的“键不存在”逻辑将运行 (2认同)
  • 如果使用 .net 4.5 不会引发异常。如果我的设置存在但包含空值或空值,则会返回误报。应该有一个 `HasKey()` 或类似的方法。Divyesh Patel 提供的答案更为正确。 (2认同)

Div*_*tel 74

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

  • 对于一个简单的事实,这是一个更好的解决方案,它实际上是检查密钥是否存在.如果我的密钥有空值,user195488提供的解决方案会给我一个误报. (8认同)
  • 此解决方案不正确.AppSettings是一个NameValueCollection,默认情况下,对于键查找,它是**不区分大小写的**.您在此处使用的LINQ .Contains扩展方法将默认为**区分大小写的**比较. (5认同)

cod*_*der 9

通过泛型和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;
}
Run Code Online (Sandbox Code Playgroud)

使用如下:

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