2012-10-17 71 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

相关问题