2009年9月22日 星期二

使用ConfigurationManager管理組態檔

使用ConfigurationManager管理組態檔
命名空間
  • System.Configuration
方法
  • OpenExeConfiguration:開啟執行中應用程式的組態檔
  • OpenMachineConfiguration:開啟本機Machine.config的組態檔
  • AppSettings:取得目前應用程式的設定資訊
  • ConnectionString:取得目前應用程式的連線字串資訊
==================================
組態檔除了可以使用文字編輯器手動編輯外,也可以利用程式碼進行控制。
ConfigurationManager可以讓程式存取本機、應用程式、使用者的組態資訊。

組態檔的使用者層級
在開啟應用程式時可以指定使用者階級,它的列舉常數名稱是ConfigurationUserLevel,包含下列列舉值:
  • None:取得套用給全部使用者的組態資訊
  • PerUserRoaming:取得套用給目前使用者的漫遊(Roamining)組態資訊
  • PerUserRoamingAndLocal:取得用給目前使用者的本機組態資訊
=>漫遊(Roamining)在網域(Domain)環境中,使用者允許漫遊於網域中其它電腦,而使用者設定檔會隨著使用者的登入而更新到登入的那台電腦。
==================================
如何開啟組態檔
  • 開啟應用程式的組態檔
config = ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
TextBox1.Text = config.FilePath
=>D:\NET\U2956A\Exercise\Mod08\Mod08\bin\Debug\Mod08.vshost.exe.config
  • 開啟本機的組態檔
config = ConfigurationManager.OpenMachineConfiguration
TextBox2.Text = config.FilePath
=>c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config
==================================
開啟應用程式組態檔的步驟如下:
1、專案須參考System.Configuration組件
2、匯入System.Configuration命名空間
3、宣告ConfigurationManager
4、呼叫ConfigurationManager類別所提供的靜態方法OpenExeConfiguration
==================================
如何存取組態
  • 修改組態檔

==================================
appSettings區段的組態存取
Windows應用程式專案必須自行開啟app.Config檔案編輯。
=>測試要到D:\NET\U2956A\Exercise\Mod08\Mod08\bin\Debug\Mod08.exe測試才會準
=>如用D:\NET\U2956A\Exercise\Mod08\Mod08\bin\Debug\Mod08.vshost.exe修改組態檔會沒有效果

程式實作
'寫入
Dim config As Configuration
config = ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
config.AppSettings.Settings("FileServer").Value = TextBox6.Text
config.Save()
'讀取
TextBox6.Text = config.AppSettings.Settings("FileServer").Value
==================================
connectionStrings區段的組態存取
'寫入
Dim config As Configuration
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.ConnectionStrings.ConnectionStrings("Mod08.My.MySettings.cnToNorthwind").ConnectionString = TextBox7.Text'可修改application層級
config.Save()
'讀取
TextBox7.Text = ConfigurationManager.ConnectionStrings( _
"Mod08.My.MySettings.cnToNorthwind").ConnectionString'如用ConfigurationManager修改Application層級會顯示只能唯讀錯誤

沒有留言:

張貼留言