Fetching dynamically updated connection string from app.config in VB.Net

房东的猫 提交于 2019-12-10 22:33:53

问题


I have a connection string as follows in app.config

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

I have a form called DBLinker where i am giving an option to the user to select some other server and database. For instance i am selecting Server name as "MAILSERVER" and database as "Actual". I am overwriting the app.config file using the following code.

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)

After this code i am trying to open a login form for the application. But when i am trying to access connection string here, it is fetching the former string instead of the updated one.


回答1:


How to programmatically override web.config settings

It looks like you can't alter web.config at Runtime and have it take effect while the application is running. You can get around this by maybe having a setting be the base part of the string and then use the user selection to build the rest. You can always save the new string in Session, cookie or a Db to keep it handy when you need it, depending on your needs.

Hope this helps.




回答2:


 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

I used this code to solve this problem.



来源:https://stackoverflow.com/questions/12928689/fetching-dynamically-updated-connection-string-from-app-config-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!