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
  • 相关阅读:
    Xshell安装教程及Xshell安装程序集组件时出错的解决方法
    Xshell远程连接的具体操作和Xshell多会话设置小技巧
    VMware中出现物理内存不足,无法使用配置的设置开启虚拟机解决方案
    在Scrapy中如何利用Xpath选择器从HTML中提取目标信息(两种方式)
    Sublime Text编辑器配置Python解释器简易教程
    虚拟机创建后该如何获取IP地址并访问互联网实用教程
    关于Scrapy爬虫项目运行和调试的小技巧(下篇)
    Spring的xml和注解对比
    Spring5.X的注解配置项目
    Spring的AOP快速实现通用日志打印
  • 原文地址:https://www.cnblogs.com/tomclock/p/7215880.html
Copyright © 2011-2022 走看看