0

I am trying the following solution and not having much luck: How can i update app.config connectionstring Datasource value in C#?

The code I have is:

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");

My app.config file has:

<?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>

Where am I going wrong?

Community
  • 1
  • 1
hshah
  • 842
  • 4
  • 14
  • 35

2 Answers2

0

I've only been fiddling with SQL CE for a few days myself, but if you're doing anything with SqlCE database, you probably want to use SqlCe classes rather than Sql ones - try SqlCeConnectionStringBuilder?

Other than that, as long as |DataSource| is supported in CE the connection string you've posted looks like the examples I've seen & used.

Jason Williams
  • 56,972
  • 11
  • 108
  • 137
  • What I ended up doing is not using the connection string in the app.config and instead set up my own XML file to read from. I will try out what you said though to see if that was where I was going wrong. – hshah Sep 04 '12 at 22:31
  • Sorry - guess the problem lies elsewhere then. – Jason Williams Sep 05 '12 at 09:26
0

I ended up creating my own XML file which stores the database string and lets the user update it if it is invalid or if they wish to connect to a different database. I think it works out better than trying to update the app.config.

hshah
  • 842
  • 4
  • 14
  • 35