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

时间:2020-03-05 18:53:37  来源:igfitidea点击:

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

解决方案

回答

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

配置myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

然后,我们可以在以下位置访问连接字符串集合:

myConfig.ConnectionStrings.ConnectionStrings

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

回答

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

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

回答

// 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);