[英]How to check if an appSettings key exists?
如何检查应用程序设置是否可用?
即 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
}
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.AllKeys.Contains("myKey"))
{
// Key exists
}
else
{
// Key doesn't exist
}
通过泛型和 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);
var isAlaCarte =
ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") &&
bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));
我认为 LINQ 表达式可能是最好的:
const string MyKey = "myKey"
if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
{
// Key exists
}
如果您要查找的密钥不存在于配置文件中,您将无法使用 .ToString() 将其转换为字符串,因为该值将为 null 并且您将获得“未设置对象引用”到对象的实例”错误。 在尝试获取字符串表示之前,最好先查看该值是否存在。
if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["myKey"]))
{
String myKey = ConfigurationManager.AppSettings["myKey"].ToString();
}
或者,正如 Code Monkey 建议的那样:
if (ConfigurationSettings.AppSettings["myKey"] != null)
{
// Now do your magic..
}
上面的选项为所有方式提供了灵活性,如果您知道密钥类型,请尝试解析它们bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);
我喜欢codebender 的回答,但需要它在 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.