不更改app.config

时间:2013-05-04 19:51:12

标签: c# visual-studio-2010 app-config

我想在app.config

中在运行时更改连接字符串

我写的代码如下:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["test"].ConnectionString = "sadasd";
//config.ConnectionStrings.SectionInformation.ForceSave = true;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

但是app.config没有改变!

1 个答案:

答案 0 :(得分:0)

您可以尝试我使用的这种方法,并在WinForms和MySQL项目中为我工作:

 private void EditConString(string connName, string user, string pwd, string server,string database)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
            connectionStringsSection.ConnectionStrings[connName].ConnectionString = "Server=" + server + ";User Id=" + user + ";password=" + pwd + ";database=" + database + ";ConnectionTimeout = 60;Allow Zero Datetime=True";
            config.Save();
            ConfigurationManager.RefreshSection("connectionStrings");
        }
祝你好运!