How can I update the value of the app.config connectionString data source in C #?

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.ConnectionStrings.ConnectionStrings["MyConnectionString",String.Format("DataSource={0};")].ConnectionString=textBox1.Text; config.Save(ConfigurationSaveMode.Modified, true); ConfigurationManager.RefreshSection("connectionStrings"); 

I have problems with the second line. It seems I can not syntax correctly. As you can see, I only want to update the value of the DataSource. For example, if the current value is Data Source = PC001 \ SQL2008EXPRESS , I want it to be updated so that the client is included in textBox1.

EDIT: ConnectionString Example

 <add name="ERPDatabaseTables" connectionString="metadata=res://*/ERPTables.csdl|res://*/ERPTables.ssdl|res://*/ERPTables.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=PC001\SQL2008EXPRESS;Initial Catalog=MyDatabase.mdf;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"/> 

so you want to update only Data Source = PC001 \ SQL2008EXPRESS

+4
source share
1 answer

Actually you want:

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Because it an EF connection string it not a normal connection string // so we pull it into the EntityConnectionStringBuilder instead EntityConnectionStringBuilder efb = new EntityConnectionStringBuilder( config.ConnectionStrings.ConnectionStrings["ERPDatabaseTables"] .ConnectionString); // Then we extract the actual underlying provider connection string SqlConnectionStringBuilder sqb = new SqlConnectionStringBuilder(efb.ProviderConnectionString); // Now we can set the datasource sqb.DataSource = textBox1.Text; // Pop it back into the EntityConnectionStringBuilder efb.ProviderConnectionString = sqb.ConnectionString; // And update... config.ConnectionStrings.ConnectionStrings["ERPDatabaseTables"] .ConnectionString = efb.ConnectionString; config.Save(ConfigurationSaveMode.Modified, true); ConfigurationManager.RefreshSection("connectionStrings"); 

This implies:

  • EF connection string exists in application configuration file

  • You have a link to System.Data.Entity

+12
source

All Articles