2010-07-20 181 views
104

如何檢查應用程序設置是否可用?如何檢查appSettings鍵是否存在?

即app.config中

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

並在的CodeFile

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

回答

160

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

我們有一個[類似SQL的IsNull函數(https://gist.github.com/eithe/5589891)在我們的圖書館,這使得檢索設置非常方便:'Dim configValue As String = Util.IsNull(ConfigurationManager.AppSettings.Get(「SettingName」),String.Empty)' – 2013-05-16 07:00:05

+7

它引發「沒有設置對象實例的對象引用」 – 2013-06-03 08:14:48

+0

不,這是錯誤的。如果「myKey」在應用程序設置xml節點中不存在,則代碼將引發異常。 – Gionata 2016-06-27 10:41:10

54
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey")) 
{ 
    // Key exists 
} 
else 
{ 
    // Key doesn't exist 
} 
+0

如果你以後不想使用這個值,這可能會稍微更有效率(?)。這個問題特別提到測試'如果應用程序設置可用'。既然可用性意味着想要在我腦海中使用它,我會說user195488提供的答案對於來到這裏的人會更有用 - 但嚴格來說,你的答案也是正確的。 – 2014-09-11 19:09:17

+5

這對於一個簡單的事實來說是一個更好的解決方案,它實際上是檢查密鑰是否存在。如果我對我的密鑰有空白值,user195488提供的解決方案會給我一個誤報。 – dyslexicanaboko 2014-09-30 19:40:53

+2

此解決方案不正確。 AppSettings是一個NameValueCollection,當涉及到鍵查找時,它默認爲**不區分大小寫**。然而,您在此處使用的LINQ .Contains擴展方法將默認爲**區分大小寫的**比較。 – Jax 2015-06-04 19:00:06

2

如果您正在查找的密鑰不在配置文件中,您將無法使用.ToString()將其轉換爲字符串,因爲該值將爲null,您將得到一個「對象引用未設置爲對象的實例」錯誤。在嘗試獲取字符串表示之前,最好先查看該值是否存在。

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

或者,如代碼猴建議:

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

上的選項給了靈活,所有的方式,如果你知道密鑰類型嘗試解析它們 bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);

3

我認爲LINQ表達可能是最佳:

const string MyKey = "myKey" 

    if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey)) 
      { 
       // Key exists 
      } 
+0

當然...但idunno - 這種方法有什麼_advantage_?如果我真的很熟悉Linq(大多數C#程序員可能最終會這樣做),那麼閱讀這個例子可能會很容易,但我認爲它不會是_easier_--所以除非有效率優勢...爲什麼? – 2014-09-11 19:12:28

+0

沒有效率優勢和語法冗長的imo。 – 2015-10-06 14:51:25

2

var isAlaCarte = Configu rationManager.AppSettings.AllKeys.Contains(「IsALaCarte」)& & bool.Parse(ConfigurationManager.AppSettings.Get(「IsALaCarte」));

3

通過泛型和LINQ安全地返回了默認值。

public T ReadAppSetting<T>(string searchKey, T defaultValue) 
{ 
    if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == searchKey)) 
    { 
     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 default 
    } 
    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);