我正在尝试以下解决方案,但运气不佳: 如何在 C# 中更新 app.config 连接字符串数据源值?
我的代码是:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Because it's an EF connection string it's not a normal connection string
// so we pull it into the EntityConnectionStringBuilder instead
EntityConnectionStringBuilder efb = new EntityConnectionStringBuilder(
config.ConnectionStrings.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.TestDBConnectionString"]
.ConnectionString);
// Then we extract the actual underlying provider connection string
SqlConnectionStringBuilder sqb = new SqlConnectionStringBuilder(efb.ProviderConnectionString);
// Now we can set the datasource
sqb.DataSource = "|DataDirectory|\\TestDBa.sdf";
// Pop it back into the EntityConnectionStringBuilder
efb.ProviderConnectionString = sqb.ConnectionString;
// And update...
config.ConnectionStrings.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.TestDBConnectionString"]
.ConnectionString = efb.ConnectionString;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
我的app.config
文件有:
<?xml version="1.0" encoding="utf-8" ?><configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="WindowsFormsApplication1.Properties.Settings.TestDBConnectionString"
connectionString="Data Source=|DataDirectory|\TestDB.sdf"
providerName="Microsoft.SqlServerCe.Client.4.0" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup></configuration>
我哪里错了?