VS2005 C#以编程方式更改app.config中包含的连接字符串

想在程序上更改一个数据库的connecton字符串,该数据库在windows应用程序中使用asp.net的成员资格提供程序。 system.configuration命名空间允许更改用户设置,但是,我们想调整应用程序设置吗? 是否需要编写一个使用XML来修改类的类? 是否需要删除当前连接(可以选择要清除的连接)并添加新连接吗? 可以调整现有的连接字符串吗?

不得不做这件事。 这是适合我的代码:

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"); 
 // Get the application configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); // Create a connection string element and // save it to the configuration file. // Create a connection string element. ConnectionStringSettings csSettings = new ConnectionStringSettings("My Connection", "LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" + "Initial Catalog=aspnetdb", "System.Data.SqlClient"); // Get the connection strings section. ConnectionStringsSection csSection = config.ConnectionStrings; // Add the new element. csSection.ConnectionStrings.Add(csSettings); // Save the configuration file. config.Save(ConfigurationSaveMode.Modified); 

您可以使用System.configuration命名空间以编程方式打开配置:

Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

然后,您可以访问连接字符串集合:

myConfig.ConnectionStrings.ConnectionStrings

您可以根据需要修改集合,并在完成时在配置对象上调用.Save()

使用ConnectionStringsSection类。 该文档甚至提供了一个如何创建新ConnectionString的示例,并让框架将其保存到配置文件中,而无需实现整个XML shebang。

请参阅此处并向下浏览以获取示例。