1

我想在运行时在 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 不会改变!

4

1 回答 1

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");
        }

祝你好运!

于 2013-05-04T20:18:39.027 回答