.NET環境下Configuration 與ConfigurationManager/ AppSettings 與 ConfigSections探討

來源:互聯網
上載者:User

標籤:app   效果   new   sans   use   --   cache   ucid   ram   

關於設定檔的設定,讀取有不少細節需要注意的。

A  一般情況下,配置文檔會預設使用其下的AppSettings屬性中的值。

 以下為普通的VB代碼實現方式: 

        Dim exeFileMap As ExeConfigurationFileMap = New ExeConfigurationFileMap()

        exeFileMap.ExeConfigFilename = configFilePath

        Dim configCache As Configuration 
= ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None)  

        Dim rtnValue = configCache.AppSettings.Settings(strKey).Value

 

B 對於客戶自訂的Section必須放在configSections中,在讀取這些Section過程時。

需要根據App.Config檔案路徑,進行判斷。

    (1) 對於預設路徑下App.Config, 可以直接用

     Dim nb As System.Collections.Hashtable
= CType(System.Configuration.ConfigurationManager.GetSection("MajorCommands"), _

System.Collections.Hashtable)

     Dim rtnValue = nb(strkey) 

    (2) 對於人為定義的路徑,即A中的情況

        Dim myParamsSection As ConfigurationSection = configCache.GetSection("USERSECTION")

        Dim myParamsSectionRawXml As String = myParamsSection.SectionInformation.GetRawXml()        Dim sectionXmlDoc As Xml.XmlDocument = New Xml.XmlDocument()        sectionXmlDoc.Load(New StringReader(myParamsSectionRawXml))        Dim handler As NameValueSectionHandler = New NameValueSectionHandler()        Dim handlerCreatedCollection As Specialized.NameValueCollection        handlerCreatedCollection = CType(handler.Create(Nothing, Nothing, sectionXmlDoc.DocumentElement), Specialized.NameValueCollection)        If Not handlerCreatedCollection.AllKeys.Contains(key) Then            Return defaultData        Else            Return handlerCreatedCollection(key)        End If

 

 設定檔中需要增加

  <configSections>    <section name ="USERSECTION"             type ="System.Configuration.DictionarySectionHandler" />  </configSections>

 <appSettings></appSettings>

 

 <USERSECTION>

 

    <!--Customize-->    <add key ="key1" value ="SHINSHO"/>    <add key ="key2" value ="SOJITZ"/>    <add key ="key3" value ="SUMITOMO"/>    <add key ="key4" value ="MITSUBISHI  ELECTRIC"/>    <add key ="key5" value ="MITSUBISHI"/>  </USERSECTION>

         

 當然,如果直接用XML讀取控制項,來實現也能達到同樣的效果。

如果再有疑惑,請直接閱讀微軟的原始碼

 https://referencesource.microsoft.com/#System.Configuration 

.NET環境下Configuration 與ConfigurationManager/ AppSettings 與 ConfigSections探討

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.