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");
我在第二行遇到麻烦。我似乎无法使语法正确。如您所见,我只想更新DataSource值。例如,如果当前值为数据源= PC001 \ SQL2008EXPRESS ,我希望将其更新为客户端在textBox1中输入的内容。
编辑:示例ConnectionString
<add name="ERPDatabaseTables" connectionString="metadata=res://*/ERPTables.csdl|res://*/ERPTables.ssdl|res://*/ERPTables.msl;provider=System.Data.SqlClient;provider connection string="Data Source=PC001\SQL2008EXPRESS;Initial Catalog=MyDatabase.mdf;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
所以想要仅更新数据源= PC001 \ SQL2008EXPRESS 部分
答案 0 :(得分:12)
你真正想要的是:
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["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");
这假设:
您的EF连接字符串存在于应用程序的配置文件
您可以参考System.Data.Entity