如何在VB.NET windows应用程序中修改app.config文件中的ConnectionString?

时间:2012-12-19 10:43:47

标签: vb.net connection-string app-config configurationmanager

我想更改app.config文件中编写的应用程序的连接字符串。我喜欢直接从我的应用程序中更改连接字符串。

我的app.config看起来像:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    ...
  <connectionStrings>
    <add name="ApplicationName.My.MySettings.ConnectionS"
      connectionString="Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="Test"   value="/"  />
  </appSettings>
</configuration>

我可以使用以下代码对 appSettings 进行更改:

Dim config As System.Configuration.Configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.AppSettings.Settings("Test").Value = "New value"

但是,当安装应用程序时,我无法在 connectionStrings 中进行更改:

Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim connectionStringsSection = DirectCast(config.GetSection("connectionStrings"), ConnectionStringsSection)
connectionStringsSection.ConnectionStrings("ApplicationName.My.MySettings.ConnectionS").ConnectionString = "New connection string"
config.Save()
ConfigurationManager.RefreshSection("connectionStrings")

2 个答案:

答案 0 :(得分:0)

要在代码中更改它,请尝试以下内容;

Dim con1 = ConfigurationManager.ConnectionStrings("connection1")
Dim con2 = ConfigurationManager.ConnectionStrings("connection2")

'connection1'和'connection2'是app.config中连接字符串的名称。

答案 1 :(得分:0)

Dim c As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim section As ConnectionStringsSection = DirectCast(c.GetSection("connectionStrings"), ConnectionStringsSection)
section.ConnectionStrings("Services.My.MySettings.hassanConnectionString").ConnectionString = createCnxString()
c.Save()


Private Function createCnxString() As String
    Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
    builder("Data Source") = datasourceTxt.Text
    builder("Integrated Security") = True
    builder("Initial Catalog") = "XXXX"
    builder("User ID") = usernameTxt.Text
    builder("Password") = passwordTxt.Text
    Return builder.ConnectionString
End Function