C#配置文件Section节点处理总结
本文实例总结了c#配置文件section节点处理方法。分享给大家供大家参考。具体如下:
很多时候在项目开发中,我们都需要用配置文件来存储一些关于程序配置信息,这时候你可以选择ini或者app.config来存储,这里对此总结一下:
配置文件示例如下:
<configuration>
<configsections>
<sectiongroup name="module">
<section name="appsettings" type="system.configuration.namevaluefilesectionhandler"/>
</sectiongroup>
</configsections>
<module>
<appsettings>
<!--谷歌地图-->
<add key="googlemap" value="1"/>
<!--箱实时状态信息汇总-->
<add key="cab_rt" value="1"/>
</appsettings>
</module>
</configuration>
操作代码如下:
using system.collections.specialized;
using system.configuration;
namespace consoleapplication38
{
class program
{
static void main(string[] args)
{
try
{
sectiontoolv2 _sectionhelper = new sectiontoolv2("module/appsettings");
console.writeline(_sectionhelper.getvalue("googlemap"));
console.writeline(_sectionhelper.containkey("yanzhiwei"));
}
catch (exception ex)
{
console.writeline(ex.message);
}
finally
{
console.readline();
}
}
}
class sectiontoolv2
{
namevaluecollection modulsettings = null;
/// <summary>
///构造函数
/// </summary>
/// <param name="sectionname">section名称</param>
public sectiontoolv2(string sectionname)
{
modulsettings = configurationmanager.getsection(sectionname) as namevaluecollection;
}
/// <summary>
/// 是否包含该section
/// </summary>
/// <returns></returns>
public bool containsection()
{
return !(modulsettings == null);
}
/// <summary>
/// section是否包含key
/// </summary>
/// <param name="key">键</param>
/// <returns>值</returns>
public bool containkey(string key)
{
if (containsection())
{
return !(modulsettings[key] == null);
}
return false;
}
/// <summary>
/// 根据键获取值
/// </summary>
/// <param name="key">键</param>
/// <returns>当不存在键的时候,返回string.empty</returns>
public string getvalue(string key)
{
string _value = string.empty;
if (containkey(key))
{
_value = modulsettings[key];
}
return _value;
}
}
}
测试效果如下:
希望本文所述对大家的c#程序设计有所帮助