開發Net. 程式開發時會將程式的參數檔案寫到app.config中
大部分使用者自訂的參數會寫在applicationSettings中
不過這樣的寫法沒有模組化
原始的applicationSettings
<applicationSettings> <My.MySettings> <setting name="HRDBSchema" serializeAs="String"> <value>HR</value> <setting name="RDDBSchema" serializeAs="String"> <value>RD</value> </setting> </My.MySettings> </applicationSettings>
config 改成下面寫法,把相關的參數寫在同一個tag 中,類似connectionStrings tag的寫法
<DBSetting> <Group DBNAME="HRDB" SCHEMA="HR"> <Group DBNAME="RDDB" SCHEMA="RD"> </DBSetting>
1. 加入System.Configuration參考
2. 在configSections中新增一個section tag
<configuration> <configSections> <section name="DBSetting" type="WindowsApplication1.MyConfigHandler, WindowsApplication1" /> </configSections> <DBSetting> <Group DBNAME="HRDB" SCHEMA="HR"> <Group DBNAME="RDDB" SCHEMA="RD"> </DBSetting> <configuration>
3. 新增DBSetting類別
Public Class DBSetting Public DBNAME As String Public SCHEMA As String End Class
4. 新增MyConfigHandler類別
Imports System Imports System.Configuration Imports System.Xml Public Class MyConfigHandler : Implements IConfigurationSectionHandler Public Function Create(ByVal parent As Object, ByVal configContext As Object, ByVal section As System.Xml.XmlNode) As Object Implements System.Configuration.IConfigurationSectionHandler.Create Dim olist As New List(Of DBSetting) Dim oSchSetting As DBSetting For Each JobNode As XmlNode In section.ChildNodes oSchSetting = New DBSetting() With oSchSetting .DBNAME = JobNode.Attributes("DBNAME").InnerText .SCHEMA = JobNode.Attributes("SCHEMA").InnerText End With olist.Add(oSchSetting) Next Return olist End Function End Class
5. 在程式中引用
Imports System.Configuration Public Class Form1 Public Sub New() ' 此為 Windows Form 設計工具所需的呼叫。 InitializeComponent() ' 在 InitializeComponent() 呼叫之後加入任何初始設定。 Dim DBList As New Generic.List(Of DBSetting) Dim DBSchemaList As New Generic.LinkedList(Of String) Dim DBSchemaDic As New Generic.Dictionary(Of String, String) ' Get Schedule Run and ETL setting from app.config DBList = CType(ConfigurationManager.GetSection("DBSetting"), Generic.List(Of DBSetting)) For Each db As DBSetting In DBList DBSchemaDic.Add(db.DBNAME, db.SCHEMA) Next End Sub End Class
文章標籤
全站熱搜
留言列表