System.Configuration

Note:本篇測試以及範例程式檔使用Visual Studio 2008
一般應用程式都會有一些設定檔,最常見的是使用文字檔來儲存相關設定,但要自行處理相關的"切割字串"的動作,比較不那麼直覺;或是有時候會使用INI檔或是登錄檔來儲存一些設定;這邊我們介紹另一種方式,使用Configuration提供的部分功能來作
首先,要使用Configuration,你必須先將System.Configuration的參考加入,像是下面這樣圖

加入參考之後我們便可以利用ConfigurationManager開始進行我們要做的功能,首先是UI的部分,我是做了像下面這樣簡單的介面來測試

有3個TextBox分別命名為txtName、txtStartDate、txtEndDate,以及兩個Button,分別是btnSave、btnReload,下面是測試的程式碼
Imports System.Configuration

Public Class Form1

Dim CG As Configuration

'''
''' 儲存設定的程式碼
'''

'''
'''
'''
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
CG.AppSettings.Settings.Item("Name").Value = txtName.Text
CG.AppSettings.Settings.Item("StartDate").Value = txtStartDate.Text
CG.AppSettings.Settings.Item("EndDate").Value = txtEndDate.Text
CG.Save(ConfigurationSaveMode.Modified)
MessageBox.Show("Save OK")
ConfigurationManager.RefreshSection("appSettings")
End Sub

'''
''' 將設定值讀出的程式碼
'''

'''
'''
'''
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReLoad.Click
Try
txtName.Text = CG.AppSettings.Settings("Name").Value
txtStartDate.Text = CG.AppSettings.Settings("StartDate").Value
txtEndDate.Text = CG.AppSettings.Settings("EndDate").Value
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CG = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

If CG.AppSettings.Settings("Name") Is Nothing Then
SetDefault()
Else
txtName.Text = CG.AppSettings.Settings("Name").Value
End If
If CG.AppSettings.Settings("StartDate") Is Nothing Then
SetDefault()
Else
txtStartDate.Text = CG.AppSettings.Settings("StartDate").Value
End If
If CG.AppSettings.Settings("EndDate") Is Nothing Then
SetDefault()
Else
txtEndDate.Text = CG.AppSettings.Settings("EndDate").Value
End If
End Sub

'''
''' 如果沒有找到設定值用Default帶入
'''

'''
Private Sub SetDefault()
If CG.AppSettings.Settings("Name") Is Nothing Then
CG.AppSettings.Settings.Add("Name", "Default")
End If
If CG.AppSettings.Settings("StartDate") Is Nothing Then
CG.AppSettings.Settings.Add("StartDate", "Default")
End If
If CG.AppSettings.Settings("EndDate") Is Nothing Then
CG.AppSettings.Settings.Add("EndDate", "Default")
End If

CG.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
End Sub
End Class

產生出來的設定檔會放在跟執行檔同樣的位置,檔案名稱會是"你的執行檔名稱.Config",如果打開來看會是下面這樣子









有一點要注意一下,程式一開始會去讀取設定檔一次,之後不會隨時的去"監看"設定檔內容的變化,所以如果你是手動去修改設定檔內容的話,你會發現重新啟動程式才會看的到效果喔。
如果你需要範例的程式檔案的話可以到這邊下載

留言

這個網誌中的熱門文章

開啟cshtml檔案時,出現『並未將物件參考設定為物件執行個體』的錯誤訊息

無法設定中斷點 尚未載入符號檔

Windows 10年度更新後,IIS 網站出現 503 錯誤