在c#

时间:2016-09-16 12:20:05

标签: c# sql-server wpf

为什么我的代码无效

的app.config

<connectionStrings>
    <add name="string.name"
        connectionString=""
        providerName="System.Data.SqlClient" />
</connectionStrings>

在c#

private void addnewstring()
    {         
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.Settings.Remove("string.name");            
        config.AppSettings.Settings.Add("string.name", "new connection string");            
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("connectionStrings");                       
    }

c#中的代码不会改变app.config中的连接字符串

2 个答案:

答案 0 :(得分:1)

您需要修改ConnectionStrings - 您的代码只是访问“设置”。试试这个:

  Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  config.ConnectionStrings.ConnectionStrings.Remove("string.name");
  config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("string.name", "new connection string"));
  config.Save(ConfigurationSaveMode.Modified);
  ConfigurationManager.RefreshSection("connectionStrings");

答案 1 :(得分:0)

试试这个,请说工作

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["string.name"].ConnectionString = "new connection string";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");