.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
.NET環境下Configuration 與ConfigurationManager/ AppSettings 與 ConfigSections探討