我想在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没有改变!
答案 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");
}
祝你好运!