想要在Windows应用程序中以编程方式更改利用asp.net成员资格提供程序的数据库的connecton字符串.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()
配置对象时完成.