简体   繁体   English

将ConnectionString保存在App.config中

[英]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: 我正在尝试使用以下方法在运行时基于每个用户在app.config中保存连接字符串:

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. 锁定后无法编辑ConfigurationSection属性。

when I try to get the ConfigurationAllowExeDefinition . 当我尝试获取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"); 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"); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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