3

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.

Yatrix
  • 13,361
  • 16
  • 48
  • 78
Shruti
  • 281
  • 2
  • 4
  • 12

2 Answers2

2

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.

Community
  • 1
  • 1
Yatrix
  • 13,361
  • 16
  • 48
  • 78
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

I used this code to solve this problem.

Shruti
  • 281
  • 2
  • 4
  • 12