162

アプリケーション設定が利用可能かどうかを確認するにはどうすればよいですか?

つまり、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
}
4

9 に答える 9

240

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
}
于 2010-07-20T23:53:26.633 に答える
91
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
    // Key exists
}
else
{
    // Key doesn't exist
}
于 2011-05-20T11:14:24.827 に答える
10

ジェネリックスと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);
于 2017-03-25T04:22:46.037 に答える
3
var isAlaCarte = 
    ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") && 
    bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));
于 2015-08-04T15:12:18.633 に答える
2

探しているキーが構成ファイルに存在しない場合、値がnullになり、「オブジェクト参照が設定されていない」というメッセージが表示されるため、.ToString()を使用して文字列に変換することはできません。オブジェクトのインスタンスへ」エラー。文字列表現を取得する前に、まず値が存在するかどうかを確認することをお勧めします。

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

または、コードモンキーが示唆したように:

if (ConfigurationSettings.AppSettings["myKey"] != null)
{
// Now do your magic..
}
于 2011-09-20T13:46:36.130 に答える
2

キータイプがわかっている場合は、上部のオプションを使用すると、あらゆる方法に柔軟に対応できます。 bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);

于 2012-03-13T19:46:59.547 に答える
2

LINQ式が最適だと思います。

   const string MyKey = "myKey"

   if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
          {
              // Key exists
          }
于 2014-02-28T16:56:13.190 に答える
1

私は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;
}
于 2019-05-25T00:56:16.863 に答える
0

TryParseで新しいc#構文を使用すると、うまくいきました。

  // TimeOut
  if (int.TryParse(ConfigurationManager.AppSettings["timeOut"], out int timeOut))
  {
     this.timeOut = timeOut;
  }
于 2019-10-31T01:50:37.453 に答える