0

我想更改写在 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")
4

2 回答 2

0

要在代码中更改它,请尝试以下操作;

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

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

于 2012-12-19T11:34:49.857 回答
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
于 2014-03-19T13:39:23.320 回答