如何检查 appSettings 键是否存在?

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

即 app.config

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

还有代码文件

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

配置管理器。应用程序设置

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

或者

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

如果要查找的键不在配置文件中,则无法使用。ToString () ,因为该值将为 null,并且您将得到一个“ Object reference not set to an instance of an Object”错误。在尝试获取字符串表示形式之前,最好先查看该值是否存在。

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

或者,就像代码猴建议的那样:

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

如果您知道键类型,那么可以尝试解析它们 bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);

我认为 LINQ 表达式可能是最好的:

   const string MyKey = "myKey"


if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
{
// Key exists
}
var isAlaCarte =
ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") &&
bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));

通过泛型和 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;
}

用法如下:

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

我喜欢 解码者的回答,但是需要它在 C + +/CLI 中工作。这就是我的结局。没有使用 LINQ,但有效。

generic <typename T> T MyClass::ReadAppSetting(String^ searchKey, T defaultValue) {
for each (String^ setting in ConfigurationManager::AppSettings->AllKeys) {
if (setting->Equals(searchKey)) { //  if the key is in the app.config
try {                           // see if it can be converted
auto converter = TypeDescriptor::GetConverter((Type^)(T::typeid));
if (converter != nullptr) { return (T)converter->ConvertFromString(ConfigurationManager::AppSettings[searchKey]); }
} catch (Exception^ ex) {} // nothing to do
}
}
return defaultValue;
}

在 TryParse 中使用新的 c # 语法对我来说效果很好:

  // TimeOut
if (int.TryParse(ConfigurationManager.AppSettings["timeOut"], out int timeOut))
{
this.timeOut = timeOut;
}