2010年11月23日

讀寫App.Config-Windows form範例

我們的windows form程式裡可能需要預設一些Connection String, 那可以用ConfigurationManager 類別 , 進行讀取和作更新, ConfigurationManager有很多屬性, 常用的有AppSetting和ConnectionStrings, 以下就模擬將資料庫連線字串和使用者帳號/密碼, 利用以上 兩屬性來實作設定和撰寫相關讀取更新程式:

新增項目-app.config文件:

右擊專案名稱,選擇“加入”→“新增項目”,在出現的“加入新項目”對話方塊中,選擇“應用程式組態檔”;如果專案以前沒有設定檔,則預設的檔名稱為“app.config”,按一下“確定”。出現在VS中的app.config文件為
<?xmlversion="1.0"encoding="utf-8" ?>

<configuration>

…….

</configuration>

加入ConnectionStrings,appSettings節點:


在app.config加入ConnectionStrings節點:
<configuration>
<connectionStrings>
<add name="myConn"
connectionString="Data Source=localhost;Initial Catalog=jxcbook;User                                   ID=sa;password=********"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="userName"value="uid" />
<add key="password"value="pwd" />
</appSettings>
<configuration/>

ConnectionStrings所內含的Tag add, 共有三個屬性
  • name:add 標籤名稱
  • connectionString:連線資訊
  • providerName: provider 名稱

範例畫面介紹

本範例開啟視窗時會將connectionString讀到輸入框, 修改完連線字串, 修改好點Save會把結果存回app.config
image

程式碼

以下程式共有四個function:
  • GetConnectionStringsConfig
  • GetAppConfig
  • UpdateConnectionStringsConfig
  • UpdateAppConfig
Imports System
Imports System.Configuration
Public Class appConfig
 Private _connAddName As String = "myConn"
 Private Sub appConfig_Load(ByVal sender As System.Object, 
  ByVal e As System.EventArgs) Handles   MyBase.Load
  Me.txtConString.Text = GetConnectionStringsConfig(_connAddName)
 End Sub
 '讀取ConnectionString
 Private Function GetConnectionStringsConfig(ByVal connectionName As String) As String
  Dim connectionString As String = 
   ConfigurationManager.ConnectionStrings  (connectionName).ConnectionString.ToString()
  Return connectionString
 End Function
'讀取AppConfig
Private Function GetAppConfig(ByVal strKey As String) As String
  For Each key As String In ConfigurationManager.AppSettings
   If key = strKey Then
    Return ConfigurationManager.AppSettings(strKey)
   End If
  Next
  Return Nothing
 End Function
  '更新ConnectionString
 Private Sub UpdateConnectionStringsConfig(ByVal newName As String, 
   ByVal newConString As String,   ByVal newProviderName As String)
  Dim isModified As Boolean = False
  '判斷連接字串是否存在
  If ConfigurationManager.ConnectionStrings(newName) IsNot Nothing Then
    isModified = True
  End If
  '新建一個連接字串實例
  Dim mySettings As New ConnectionStringSettings(newName, newConString, newProviderName)
  ' 打開設定檔*.exe.config
  Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
  ' 如果連接串已存在,先刪除它
  If isModified Then
    config.ConnectionStrings.ConnectionStrings.Remove(newName)
  End If
  ' 將新的連接串加到設定檔中.
  config.ConnectionStrings.ConnectionStrings.Add(mySettings)
  ' 儲存設定檔所作的更改
  config.Save(ConfigurationSaveMode.Modified)
  ' 強制重新載入設定檔的ConnectionStrings配置節點
  ConfigurationManager.RefreshSection("ConnectionStrings")

 End Sub
 '更新AppConfig
 Private Sub UpdateAppConfig(ByVal newKey As String, 
  ByVal newValue As String)
  Dim isModified As Boolean = False
  For Each key As String In ConfigurationManager.AppSettings
   If key = newKey Then
    isModified = True
   End If
  Next

  ' 打開設定檔*.exe.config
  Dim config As Configuration = 
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
  ' 如果連接串已存在,先刪除它
  If isModified Then
    config.AppSettings.Settings.Remove(newKey)
  End If
  ' 將新的連接串加到設定檔中.
  config.AppSettings.Settings.Add(newKey, newValue)
  ' 儲存設定檔所作的更改
  config.Save(ConfigurationSaveMode.Modified)
  ' 強制重新載入設定檔的ConnectionStrings配置節點
  ConfigurationManager.RefreshSection("appSettings")
 End Sub

 Private Sub Button1_Click(ByVal sender As System.Object, 
  ByVal e As System.EventArgs) Handles Button1.Click

  '讀出provider nname
  Dim providerName As String = 
  ConfigurationManager.ConnectionStrings(_connAddName).ProviderName.ToString()

  UpdateConnectionStringsConfig(_connAddName, Me.txtConString.Text, providerName)
 End Sub
End Class

加密

第一步:先將目錄下的App.config改名為Web.config。
第二步:打開VS命令提示字元,輸入命令:aspnet_regiis -pef "配置節" "目錄"
可參考:
http://msdn.microsoft.com/zh-tw/library/zhhddkxy(v=VS.80).aspx
http://blog.ncuhome.cn/youngpig/Logs/2010/3/15/36456.html

參考:

http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
http://msdn.microsoft.com/zh-tw/library/system.configuration.configurationmanager(v=VS.80).aspx
http://www.cnblogs.com/xshy3412/archive/2007/11/24/971374.html

1 則留言:

  1. 您好:
    參考了您的程式碼,有個問題想請教
    我在VS2005開發環境上,加入您上述的程式碼,但是測試時,都沒有成功更改任何的文字
    是不是要封裝部署後,才能有動作?
    請指教!

    回覆刪除