9

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

4

4 回答 4

9

不得不做这件事。这是对我有用的代码:

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");
于 2012-01-09T22:49:19.320 回答
8
// 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);
于 2008-09-15T14:59:49.307 回答
6

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

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

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

myConfig.ConnectionStrings.ConnectionStrings

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

于 2008-09-15T14:50:11.513 回答
0

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

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

于 2008-09-15T14:56:13.760 回答