[英]VS2005 C# Programmatically change connection string contained in app.config
想要在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()
。
使用ConnectionStringsSection類。 該文檔甚至提供了一個如何創建新ConnectionString的示例,並讓框架將其保存到配置文件中,而無需實現整個XML shebang。
請參閱此處並向下瀏覽以獲取示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.