下面我给出一个简单的例子说明如何使用 WebConfigurationManager操作配置文件:
//
打开配置文件
Configuration config = WebConfigurationManager.OpenWebConfiguration( " ~ " );
// 获取appSettings节点
AppSettingsSection appSection = (AppSettingsSection)config.GetSection( " appSettings " );
// 在appSettings节点中添加元素
appSection.Settings.Add( " addkey1 " , " key1's value " );
appSection.Settings.Add( " addkey2 " , " key2's value " );
config.Save();
Configuration config = WebConfigurationManager.OpenWebConfiguration( " ~ " );
// 获取appSettings节点
AppSettingsSection appSection = (AppSettingsSection)config.GetSection( " appSettings " );
// 在appSettings节点中添加元素
appSection.Settings.Add( " addkey1 " , " key1's value " );
appSection.Settings.Add( " addkey2 " , " key2's value " );
config.Save();
运行代码之后可以看见配置文件中的改变:
<
appSettings
>
< add key = " addkey1 " value = " key1's value " />
< add key = " addkey2 " value = " key2's value " />
</ appSettings >
< add key = " addkey1 " value = " key1's value " />
< add key = " addkey2 " value = " key2's value " />
</ appSettings >
修改和删除节点或属性也非常方便:
//
打开配置文件
Configuration config = WebConfigurationManager.OpenWebConfiguration( " ~ " );
// 获取appSettings节点
AppSettingsSection appSection = (AppSettingsSection)config.GetSection( " appSettings " );
// 删除appSettings节点中的元素
appSection.Settings.Remove( " addkey1 " );
// 修改appSettings节点中的元素
appSection.Settings[ " addkey2 " ].Value = " Modify key2's value " ;
config.Save();
Configuration config = WebConfigurationManager.OpenWebConfiguration( " ~ " );
// 获取appSettings节点
AppSettingsSection appSection = (AppSettingsSection)config.GetSection( " appSettings " );
// 删除appSettings节点中的元素
appSection.Settings.Remove( " addkey1 " );
// 修改appSettings节点中的元素
appSection.Settings[ " addkey2 " ].Value = " Modify key2's value " ;
config.Save();
配置文件:
<
appSettings
>
< add key = " addkey2 " value = " Modify key2's value " />
</ appSettings >
< add key = " addkey2 " value = " Modify key2's value " />
</ appSettings >
参考: http://msdn2.microsoft.com/en-us/library/ms228060.aspx