本文实例总结了C#配置文件Section节点处理方法。分享给大家供大家参考。具体如下:
很多时候在项目开发中,我们都需要用配置文件来存储一些关于程序配置信息,这时候你可以选择INI或者app.config来存储,这里对此总结一下:
配置文件示例如下:
复制代码 代码如下:
操作代码如下:
复制代码 代码如下:using System;
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;
///
///构造函数
///
/// section名称
public SectionToolV2(string sectionName)
{
ModulSettings = ConfigurationManager.GetSection(sectionName) as NamevalueCollection;
}
///
/// 是否包含该Section
///
///
public bool ContainSection()
{
return !(ModulSettings == null);
}
///
/// Section是否包含Key
///
/// 键
///
public bool ContainKey(string key)
{
if (ContainSection())
{
return !(ModulSettings[key] == null);
}
return false;
}
///
/// 根据键获取值
///
/// 键
///
public string GetValue(string Key)
{
string _value = string.Empty;
if (ContainKey(Key))
{
_value = ModulSettings[Key];
}
return _value;
}
}
}
测试效果如下:
希望本文所述对大家的C#程序设计有所帮助



