troubleshooting Question

vb.net VS2008 changing connection string in app.config or machine.config

Avatar of donhannam
donhannamFlag for New Zealand asked on
.NET ProgrammingVisual Basic.NET
12 Comments1 Solution1153 ViewsLast Modified:
I am looking at using the app.config or machine.config to store connection information to an MSSQL database ideally encrypted. Windows forms application.

I can set up the connection in the app or machine config and use it fine but I have issues where I want to change the connection string - e.g. if password changes. Attached code is run from a form to set up the connection string. If it exists I would like it to update the existing info.

appreciate any help.
Private Shared Sub WriteEncryptedConnectionStringSection(ByVal name As String, ByVal constring As String, ByVal provider As String)

        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
        Dim section As ConnectionStringsSection = config.ConnectionStrings

        If section Is Nothing Then
            section = New ConnectionStringsSection
            config.Sections.Add("connectionSettings", section)

        End If

        If Not section.SectionInformation.IsProtected Then
            section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider")
        End If

        Dim csExisting As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("ConnectionString2")
        If Not csExisting Is Nothing Then
            'Update connection string ** This is where I want to update existing connection
            'csExisting.ConnectionString = constring
        Else
            Dim cs As New ConnectionStringSettings(name, constring, provider)
            section.ConnectionStrings.Add(cs)
            section.SectionInformation.ForceSave = True
        End If

        config.Save(ConfigurationSaveMode.Full)

    End Sub
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 12 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros