2014-04-18 26 views
0

我正在經歷如何在app.config的configsection中創建節組和節。 所以,讓我們採取抽樣app.config中的節類型

<configSections> 
    <sectionGroup name="trackGroup"> 
    <section name="trackInfo" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> 
    </configSections> 
    <trackGroup> 
    <trackInfo> 
    <add key = "ASHUM" value="ASH-UM"/> 
    </trackInfo> 
</trackGroup> 

所以現在當我正在經歷我發現,大家對於部分 使用不同的類型,因此各種文章,我發現這裏的不同的類型: http://msdn.microsoft.com/en-us/library/aa309408%28v=vs.71%29.aspx

但我使用的類型在這裏沒有提及。 我從一個隨機的例子中得到了這個類型,並且據我所知,它實際上是定義了appsetting部分的設置。 有人能幫助我什麼類型在我的示例中意味着什麼是版本,公共令牌,文化我們如何定義這些? 另外我想知道哪種類型更適合使用? 就像我必須在運行時訪問這些設置,甚至在運行時修改一些設置。

另外我想這些不同類型有不同的方式,我們可以訪問它們? 就像在上面的情況下我的樣品中,我訪問鍵和值:

static void getFull(string sectionName) 
     { 
      System.Collections.Specialized.NameValueCollection section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection(sectionName); 
      if (section != null) 
      { 
       foreach (string key in section.AllKeys) 
       { 
        Console.WriteLine(key + ": " + section[key]); 
       } 
      } 
     } 

但是如果我們用類型,比如那些在提供我會如何訪問鍵和值的MSDN鏈接?

回答

1

這是我爲創建配置節所做的事情。它也允許外部化部分。

的App.config

<?xml version="1.0"?> 
<configuration> 
    <configSections> 
     <section name="TrackInfo" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> 
    </configSections> 

    <TrackInfo configSource="TrackInfo.config"/> 
</configuration> 

TrackInfo.config

<?xml version="1.0" encoding="utf-8" ?> 
<TrackInfo> 
    <add key="SOME_KEY" value="SOME_VALUE" /> 
</TrackInfo> 

C#

NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("TrackInfo"); 
if(null == section) throw new Exception("Missing TrackInfo.config"); 

string val = section["SOME_KEY"]; 
+0

版本= 4.0.0.0,文化=中性公鑰= b03f5f7f11d50a3a「/>它是如何決定的?我可以給任何版本任何令牌嗎? – Silver

+0

不是100%確定,但我認爲它需要匹配.net框架。我用3.5.0.0和4.0.0.0 – texel

+0

是啊我也這麼認爲,但當我在3.5框架中使用Version = 3.5.0.0項目時,它給了我錯誤..版本= 2.0.0.0爲我工作正常直到現在 – Silver