1. 程式人生 > >C#使用ConfigurationManager類操作配置檔案

C#使用ConfigurationManager類操作配置檔案

.net1.1中如果需要靈活的操作和讀寫配置檔案並不是十分方便,一般都會在專案中封裝一個配置 檔案管理類來進行讀寫操作。而在.net2.0中使用configurationmanager 和webconfigurationmanager 類可以很好的管理配置檔案,configurationmanager類在system.configuration中, webconfigurationmanager在system.web.configuration中。根據msdn的解釋,對於 web 應用程式配置,建議使用 System.Web.Configuration.WebConfigurationManager 類

,而不要使用 system.configuration.configurationmanager 類。

下面我給出一個簡單的例子說明如何使用webconfigurationmanager操作配置檔案:
//開啟配置檔案
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
//獲取appsettings節點
AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");
//在appsettings節點中新增元素
appsection.Settings.Add("addkey1", "key1s value");
appsection.Settings.Add("addkey2", "key2s value");
config.Save();

執行程式碼之後可以看見配置檔案中的改變:

<appsettings>
<add key="addkey1" value="key1s value" />
<add key="addkey2" value="key2s value" />
</appsettings>
修改和刪除節點或屬性也非常方便:

//開啟配置檔案
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
//獲取appsettings節點
AppSettingsSection appsection = ( AppSettingsSection)config.GetSection("appSettings");
//刪除appsettings節點中的元素
appsection.Settings.Remove("addkey1");
//修改appsettings節點中的元素
appsection.Settings["addkey2"].Value = "modify key2s value";
config.Save();
配置檔案:
<appsettings>
<add key="addkey2" value="modify key2s value" />
</appsettings>
===============================================================================

往web.config中寫資料庫連線字串

protected void Page_Load(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();

builder.DataSource = "localhost";
builder.InitialCatalog = "Northwind1";
builder.UserID = "sa";
builder.Password = "password";
builder.PersistSecurityInfo = true;

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
//config.ConnectionStrings.ConnectionStrings["AppConnectionString"].ConnectionString = builder.ConnectionString;
AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");
appsection.Settings.Add("connstr", builder.ConnectionString);
config.Save();
}