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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值