2012-10-17 72 views
3

我有一個連接字符串中的app.config如下從app.config中抓取動態更新連接字符串在VB.Net

<add name="CONN" connectionString="SERVER=SERVER\SQLEXPRESS;DATABASE=TRIAL_LINK;uid=sa;pwd=trial" 
     providerName="System.Data.SqlClient" /> 

我有一個名爲DBLinker這裏我給一個選項給用戶的形式選擇一些其他服務器和數據庫。 例如,我選擇「服務器名稱」作爲「MAILSERVER」和數據庫作爲「實際」。我使用下面的代碼覆蓋app.config文件。

Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) 

Dim mySection As ConnectionStringsSection = DirectCast(config.GetSection("CONN"),ConnectionStringsSection) 
Dim conStr As String = "SERVER=MAILSERVER;DATABASE=Actual;uid=sa;pwd=trial" 

config.ConnectionStrings.ConnectionStrings("CONN").ConnectionString = conStr 
config.Save(ConfigurationSaveMode.Full) 


ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name) 

此代碼後,我試圖打開登錄窗體的應用程序。但是,當我試圖訪問連接字符串在這裏,它正在提取前字符串,而不是更新的字符串。

回答

1
Public Sub updateConfigFile(ByVal con As String) 
     'updating config file 
     Dim XmlDoc As New XmlDocument() 
     'Loading the Config file 
     XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) 
     For Each xElement As XmlElement In XmlDoc.DocumentElement 
      If xElement.Name = "connectionStrings" Then 
       'setting the coonection string 
       xElement.FirstChild.Attributes(2).Value = con 
      End If 
     Next 
     'writing the connection string in config file 
     XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) 
    End Sub 

我用這段代碼解決了這個問題。

2

How to programmatically override web.config settings

它看起來就像你不能在運行時改變的web.config並讓應用程序運行時纔會生效。你可以通過讓一個設置成爲字符串的基本部分來解決這個問題,然後使用用戶選擇來構建其餘部分。您可以隨時將新字符串保存在Session,Cookie或Db中,以便在需要時隨時保持方便,具體取決於您的需求。

希望這會有所幫助。

+1

謝謝但是這個程序不能用DB來實現。 – Shruti

相關問題