簡體   English   中英

如何從winform app.config中獲取部分?

[英]How do I get a section from my winform app.config?

我已經在這里查看了答案,但是我的問題似乎與其他人報告的Null返回值有所不同。

我正在嘗試從app.config中抓取一部分,以便可以對每個名稱/值對進行一些處理。 由於投放問題,我似乎無法從ConfigurationManager找回聯系。

使用C#和.NET 4.5,我一直在嘗試對該主題進行各種更改:

AppSettingsSection sec =
    (AppSettingsSection)ConfigurationManager.GetSection("appSettings");

我首先嘗試將這些值拉回泛型,然后使用預期的轉換錯誤來定義傳入集合的類型。 但是,我嘗試使用的每種類型都會收到相同的錯誤,無法將abc類型轉換為abc (相同類型)。

顯然問題出在椅子和鍵盤之間,但Google沒有幫助。 有任何想法嗎?

這是app.config的片段

<add key="TemplatePath" value="c:\temp\templates\"/>
<add key="deployDateToken" value="[deployDate]"/>
<add key="NavigateToFolderToken" value="[NavigateToFolder]"/>
<add key="contactToken" value="[ContactInfo]"/>

您可以這樣說:

public static IEnumerable<KeyValuePair<string,string>> EnumerateAppSettings()
{
  return ConfigurationManager
         .AppSettings
         .Cast<string>()
         .Select( key => new KeyValuePair<string,string>( key , ConfigurationManager.AppSettings[key] ) )
         ;
}

...

foreach ( KeyValuePair<string,string> item in EnumerateAppSettings() )
{
   // do something
}

甚至

Dictionary<string,string> appSettings = ConfigurationManager
                                        .AppSettings
                                        .Cast<string>()
                                        .ToDictionary( key => key , key => ConfigurationManager.AppSettings[key] )
                                        ;

或者...最簡單的:

NameValueCollection appSettings = ConfigurationManager.AppSettings ;

如果要獲取實際的AppSettingsSection ,則需要查看以下問題的答案: 如何將Web.config appSettings作為ConfigurationSection而不是NameValueCollection

那下面的東西呢

var appSettings = ConfigurationManager.AppSettings;

foreach (var key in appSettings.AllKeys)
{
    appSettings[key]//do something
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM