dimanche 10 mai 2015

How can I save connection string at run time in App.config file with vb.net?

I tried to save the connection string in the App.confing file at the run time, then I opened the file during the application was running, and I found the connection string had been saved in the file, but after I closed the application the connection string had been deleted automatically.

Can you help me to keep the connection string in the app.config file? I added two textboxes to the form (txtServer and txtDatabase) and one button to connect to database when the user click it.

Imports System.Data.SqlClient
Imports System.Text
Imports System.Configuration
Imports System.Xml

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        Dim strConnectionStringName As String = "con"
        Dim Con As StringBuilder = New StringBuilder("Data Source=")
        Con.Append(txtServer.Text)
        Con.Append(";Initial Catalog=")
        Con.Append(txtDatabase.Text)
        Con.Append(";Integrated Security=SSPI;")
        Con.Append("User ID=username; Password=xyz;")

        Dim ConStringSettings As New ConnectionStringSettings(strConnectionStringName, Con.ToString)
        Dim Config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        AddAndSaveOneConnectionStringSettings(Config, ConStringSettings)

        Catch ex As Exception
        MessageBox.Show(ConfigurationManager.ConnectionStrings("con").ToString() & _
            "This is invalid connection", "Incorrect server/Database.")
    End Try
End Sub

Public Sub AddAndSaveOneConnectionStringSettings(ByVal Config As Configuration, _
            ByVal ConStringSettings As ConnectionStringSettings)
    Dim ConStringsSection As ConnectionStringsSection = Config.ConnectionStrings
    ConStringsSection.ConnectionStrings.Add(ConStringSettings)
    Config.Save(ConfigurationSaveMode.Minimal)
    ConfigurationManager.RefreshSection("connectionStrings")
End Sub
End Class

Aucun commentaire:

Enregistrer un commentaire