简体   繁体   中英

Saving ConnectionString in App.config

I'm trying to use the following method to save connection strings in the app.config at run time on a per user basis:

public void saveConnectionString(string serverName, string conn)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    var connectionString = config.ConnectionStrings.ConnectionStrings[serverName];
    config.ConnectionStrings.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
    if (connectionString == null)
    {
        config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings
        {
            Name = serverName,
            ConnectionString = conn,
            ProviderName = "System.Data.SqlClient"
        });

        config.Save(ConfigurationSaveMode.Modified);
    }
    else
    {
        connectionString.ConnectionString = conn;
    }
}

I'm getting an exception:

ConfigurationSection properties cannot be edited when locked.

when I try to get the ConfigurationAllowExeDefinition . Is there a way round this of do I need to create my own section?

Try with below code after the code config.Save :-

ConfigurationManager.RefreshSection("connectionStrings");

We cant add to ConfigurationManager.ConnectionStrings using ConfigurationManager.ConnectionStrings.Add(connectionStringSettings) -- This fails.
But we can add to the configuration section and refresh the ConfigurationManager.

public static void AddConnectionStringSettings(
       System.Configuration.Configuration config,
       System.Configuration.ConnectionStringSettings conStringSettings)

{   
   ConnectionStringsSection connectionStringsSection = config.ConnectionStrings; 
  connectionStringsSection.ConnectionStrings.Add(conStringSettings);  
  config.Save(ConfigurationSaveMode.Minimal); 
  ConfigurationManager.RefreshSection("connectionStrings"); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM