【问题标题】:VS2005 C# Programmatically change connection string contained in app.configVS2005 C# 以编程方式更改 app.config 中包含的连接字符串
【发布时间】:2010-09-08 23:28:12
【问题描述】:
希望以编程方式更改数据库的连接字符串,该数据库在 Windows 应用程序中利用 asp.net 的成员资格提供程序。 system.configuration 命名空间允许更改用户设置,但是,我们想调整应用程序设置吗?是否需要使用 XML 编写一个类来修改该类?是否需要删除当前连接(可以选择一个连接清除)并添加一个新连接?可以调整现有的连接字符串吗?
【问题讨论】:
标签:
c#
.net
winforms
configuration
【解决方案1】:
您可以使用 System.configuration 命名空间以编程方式打开配置:
Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
然后您可以在以下位置访问连接字符串集合:
myConfig.ConnectionStrings.ConnectionStrings
您可以随意修改集合,完成后在配置对象上调用.Save()。
【解决方案2】:
使用 ConnectionStringsSection 类。该文档甚至提供了一个示例,说明如何创建新的 ConnectionString 并让框架将其保存到配置文件中,而无需实现整个 XML shebang。
请参阅here 并向下浏览示例。
【解决方案3】:
// 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);
【解决方案4】:
必须做这件事。这是对我有用的代码:
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");