如何在运行时在App

如何在运行时在App

本文介绍了如何在运行时在App.config文件中保存连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在运行时将连接字符串保存在App.confing文件中,然后我在应用程序运行期间打开了文件,我发现连接字符串已保存在文件中,但在我之后关闭应用程序连接字符串已被自动删除。



你能帮我保持app.config文件中的连接字符串吗?我在表单中添加了两个文本框(txtServer和txtDatabase),并在用户单击时添加了一个用于连接数据库的按钮。



I tried to save the connection string in the App.confing file at the run time, then I opened the file during the application while it 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

推荐答案


这篇关于如何在运行时在App.config文件中保存连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:35