zoukankan      html  css  js  c++  java
  • .NET环境下Configuration 与ConfigurationManager/ AppSettings 与 ConfigSections探讨

    关于配置文件的设置,读取有不少细节需要注意的。

    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 

    Love it, and you live without it
  • 相关阅读:
    oAuth 认证
    Javascript事件循环机制 浅尝手记
    Javascript闭包与作用域this
    SASS笔记
    FragmentActivity和Activity的区别及何时使用两者
    在fragment中获取Application数据
    Android中得到view在父容器中的位置下标
    设置android模拟器每次启动都按一定比例显示
    eclipse 导入web项目包
    拷贝Eclipse Workspace的设置
  • 原文地址:https://www.cnblogs.com/tomclock/p/7215880.html
Copyright © 2011-2022 走看看