Как проверить, существует ли ключ 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
}
Ответы
Ответ 1
MSDN: Configuration Manager.AppSettings
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
}
Ответ 2
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
// Key exists
}
else
{
// Key doesn't exist
}
Ответ 3
Безопасно вернул значение по умолчанию через дженерики и 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);
Ответ 4
Если ключ, который вы ищете, отсутствует в файле конфигурации, вы не сможете преобразовать его в строку с .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..
}
Ответ 5
Верхние параметры дают гибкость всем, если вы знаете, что тип ключа попробует их разбор
bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);
Ответ 6
Я думаю, что выражение LINQ может быть лучше:
const string MyKey = "myKey"
if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
{
// Key exists
}
Ответ 7
var isAlaCarte = ConfigurationManager.AppSettings.AllKeys.Contains( "IsALaCarte" ) && & && bool.Parse(ConfigurationManager.AppSettings.Get( "IsALaCarte" ));
Ответ 8
Мне понравился кодовый ответ, но он нужен для работы в 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;
}