问题描述
我在app.config中有一个连接字符串,如下所示:
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" />
我有一个名为DBLinker的表单,在该表单中,我向用户提供了一个选择其他服务器和数据库的选项.例如,我选择服务器名称为"MAILSERVER",数据库选择为"Actual".我正在使用以下代码覆盖app.config文件.
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.
推荐答案
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.
这篇关于从VB.Net中的app.config获取动态更新的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!