从app.config动态获取连接字符串在VB.Net中

3

我在app.config中有以下连接字符串:

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

我有一个名为DBLinker的表格,在其中给用户提供了选择其他服务器和数据库的选项。 例如,我选择服务器名称为“MAILSERVER”和数据库为“Actual”。我使用以下代码覆盖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)

在这段代码之后,我尝试打开应用程序的登录表单。但是当我在这里尝试访问连接字符串时,它获取的是旧的字符串而不是更新后的。

2个回答

2

如何在程序中覆盖web.config设置

看起来您不能在运行时更改web.config并使其在应用程序运行时生效。您可以通过将设置作为字符串的基本部分,然后使用用户选择构建其余部分来解决此问题。根据您的需求,您可以始终将新字符串保存在Session、cookie或Db中以保持方便。

希望这有所帮助。


1
谢谢,但这个过程无法使用数据库实现。 - Shruti

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

我使用这段代码来解决这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接