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

前端 未结 1 841
我寻月下人不归
我寻月下人不归 2021-01-13 23:22
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[\"MyConnectionString\",Stri         


        
相关标签:
1条回答
  • 2021-01-14 00:10

    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

    0 讨论(0)
提交回复
热议问题