.Net2.0 使用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();
}

你可能感兴趣的:(configuration)