更改连接string并在运行时重新加载app.config

当我使用此代码更改连接string时,它不会在运行时重新加载app.config 。 我期望它重新加载类似于我们如何重新加载app.config

 config.ConnectionStrings.ConnectionStrings["JVVNL_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString; config.ConnectionStrings.ConnectionStrings["CMS_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString; config.Save(ConfigurationSaveMode.Modified,true); ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.SectionName); 

必须做到这一点确切的事情。 这是我工作的代码:

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings"); connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah"; config.Save(); ConfigurationManager.RefreshSection("connectionStrings"); 

IIRC,ConfigurationManager.RefreshSection需要一个string参数,指定要刷新的部分的名称:

 ConfigurationManager.RefreshSection("connectionStrings"); 

我认为ASP.NET应用程序应该在ConnectionStrings元素被修改时自动重新加载,并且不需要手动重新加载configuration。

 //You can apply the logic in "Program.cs" //Logic for getting new connection string //**** // MyDBName="mydb"; // //**** //Assign new connection string to a variable string newCnnStr = a="Data Source=.\SQLExpress;Initial Catalog=" + MyDBName + ";Persist Security Info=True;User ID=sa;Password=mypwd"; //And Finally replace the value of setting Properties.Settings.Default["Nameof_ConnectionString_inSettingFile"] = newCnnStr; //This method replaces the value at run time and also don't needs app.config for the same setting. It will have the va;ue till the application runs. //It worked for me. 

您也可以刷新整个configuration:

 ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName]; if (importToConnectionString == null) { importToConnectionString = new ConnectionStringSettings(); importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString; importToConnectionString.ProviderName = importFromConnectionString.ProviderName; importToConnectionString.Name = newName; currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString); } else { importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString; importToConnectionString.ProviderName = importFromConnectionString.ProviderName; } Properties.Settings.Default.Reload(); 

是的,当ASP.NET web.config更新时,整个应用程序重新启动,这意味着web.config被重新加载。

首先,您可能要添加

 using System.Configuration; 

到您的.cs文件。 如果不可用,请通过“项目参考”添加它,因为它在默认情况下不包括在新项目中。

这是我解决这个问题的方法。 首先,我创build了ConnectionProperties类,它保存了我需要在原始连接string中进行更改的项目。 ConnectionProperties类中的_namevariables对于connectionString的名称非常重要第一个方法接受连接string并使用新值更改所需的选项。

 private String changeConnStringItem(string connString,string option, string value) { String[] conItems = connString.Split(';'); String result = ""; foreach (String item in conItems) { if (item.StartsWith(option)) { result += option + "=" + value + ";"; } else { result += item + ";"; } } return result; } 

你可以改变这个方法来适应你自己的需求。 我有两个mysql和mssql连接,所以我需要他们两个。 当然,你可以为自己完善这个草稿。

 private void changeConnectionSettings(ConnectionProperties cp) { var cnSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); String connString = cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString; connString = changeConnStringItem(connString, "provider connection string=\"data source", cp.DataSource); connString = changeConnStringItem(connString, "provider connection string=\"server", cp.DataSource); connString = changeConnStringItem(connString, "user id", cp.Username); connString = changeConnStringItem(connString, "password", cp.Password); connString = changeConnStringItem(connString, "initial catalog", cp.InitCatalogue); connString = changeConnStringItem(connString, "database", cp.InitCatalogue); cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString = connString; cnSection.Save(); ConfigurationManager.RefreshSection("connectionStrings"); } 

由于我不想添加微不足道的信息,我忽略了代码的属性区域。 请添加它,如果你想这个工作。

 class ConnectionProperties { private String _name; private String _dataSource; private String _username; private String _password; private String _initCatalogue; /// <summary> /// Basic Connection Properties constructor /// </summary> public ConnectionProperties() { } /// <summary> /// Constructor with the needed settings /// </summary> /// <param name="name">The name identifier of the connection</param> /// <param name="dataSource">The url where we connect</param> /// <param name="username">Username for connection</param> /// <param name="password">Password for connection</param> /// <param name="initCat">Initial catalogue</param> public ConnectionProperties(String name,String dataSource, String username, String password, String initCat) { _name = name; _dataSource = dataSource; _username = username; _password = password; _initCatalogue = initCat; } // Enter corresponding Properties here for access to private variables } 

//这里是如何在Windows App.Config中完成的

 public static bool ChangeConnectionString(string Name, string value, string providerName, string AppName) { bool retVal = false; try { string FILE_NAME = string.Concat(Application.StartupPath, "\\", AppName.Trim(), ".exe.Config"); //the application configuration file name XmlTextReader reader = new XmlTextReader(FILE_NAME); XmlDocument doc = new XmlDocument(); doc.Load(reader); reader.Close(); string nodeRoute = string.Concat("connectionStrings/add"); XmlNode cnnStr = null; XmlElement root = doc.DocumentElement; XmlNodeList Settings = root.SelectNodes(nodeRoute); for (int i = 0; i < Settings.Count; i++) { cnnStr = Settings[i]; if (cnnStr.Attributes["name"].Value.Equals(Name)) break; cnnStr = null; } cnnStr.Attributes["connectionString"].Value = value; cnnStr.Attributes["providerName"].Value = providerName; doc.Save(FILE_NAME); retVal = true; } catch (Exception ex) { retVal = false; //Handle the Exception as you like } return retVal; }