2012-09-04 77 views
0

我嘗試以下解決方案,運氣不好: How can i update app.config connectionstring Datasource value in C#?C#和SQL Server CE - 數據源關鍵字不支持

我的代碼是:

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> 

我在哪裏出錯了?

回答

0

我最終創建了自己的XML文件,它存儲數據庫字符串,並讓用戶在無效或希望連接到不同的數據庫時更新它。我認爲它比嘗試更新app.config更好。

0

我一直在自己擺弄SQL CE幾天,但如果你正在做任何與SqlCE數據庫,你可能想使用SqlCe類而不是Sql - 試試SqlCeConnectionStringBuilder

除此之外,只要| DataSource |在CE中支持您所發佈的連接字符串看起來像我見過的使用&的示例。

+0

我最終做的是不使用app.config中的連接字符串,而是設置我自己的XML文件來讀取。我會嘗試一下你說的話,看看這是不是我出錯的地方。 – hshah

+0

仍然是一樣的錯誤:( – hshah

+0

對不起 - 猜猜問題在於別處。 –