0

我正在尝试以下解决方案,但运气不佳: 如何在 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>

我哪里错了?

4

2 回答 2

0

我自己只是在几天内摆弄 SQL CE,但是如果您正在使用 SqlCE 数据库做任何事情,您可能想要使用 SqlCe 类而不是 Sql 类 - 试试SqlCeConnectionStringBuilder

除此之外,只要 |DataSource| 在 CE 中受支持您发布的连接字符串看起来像我见过和使用的示例。

于 2012-09-04T22:08:16.990 回答
0

我最终创建了自己的 XML 文件,该文件存储了数据库字符串,并让用户在它无效或希望连接到不同的数据库时对其进行更新。我认为它比尝试更新 app.config 效果更好。

于 2012-09-09T14:10:33.963 回答