How can i update app.config connectionstring Datasource value in C#?

喜夏-厌秋 提交于 2019-12-19 08:57:34

问题


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'm having trouble at line two. I cant seem to get the syntax correct. As you can see, i only want to update the DataSource value only. For example, if current value is Data Source=PC001\SQL2008EXPRESS, i want it to be updated to what the client enters in textBox1.

EDIT: Example 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=PC001\SQL2008EXPRESS;Initial Catalog=MyDatabase.mdf;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"/>

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


回答1:


What you actually want 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["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 presumes:

  1. Your EF connection string exists in the app's config file

  2. You have a reference to System.Data.Entity



来源:https://stackoverflow.com/questions/7174604/how-can-i-update-app-config-connectionstring-datasource-value-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!