如何在C#中更新app.config connectionstring数据源值()

但使书种多,会有岁稔时。这篇文章主要讲述如何在C#中更新app.config connectionstring数据源值?相关的知识,希望能为你提供帮助。

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值。例如,如果当前值是Data Source = PC001SQL2008EXPRESS,我希望它更新为客户端在textBox1中输入的内容。
【如何在C#中更新app.config connectionstring数据源值()】编辑:示例ConnectionString
< add name="ERPDatabaseTables" connectionString="metadata=res://*/ERPTables.csdl|res://*/ERPTables.ssdl|res://*/ERPTables.msl; provider=System.Data.SqlClient; provider connection string=& quot; Data Source=PC001SQL2008EXPRESS; Initial Catalog=MyDatabase.mdf; Integrated Security=True; MultipleActiveResultSets=True& quot; " providerName="System.Data.EntityClient"/>

所以想要仅更新Data Source = PC001SQL2008EXPRESS部分
答案你真正想要的是:
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");

这假定:
  1. 您的EF连接字符串存在于应用程序的配置文件中
  2. 你有参考System.Data.Entity

    推荐阅读