App.config文件如下:
读取自定义配置文件:
第一步,先创建configuration section类
public class CompanySection
{
public CompanySection()
{
}
public CompanySection(XmlNode company)
{
XmlElement c = (XmlElement)company;
_enabled = Convert.ToBoolean(c.Attributes["Enabled"].Value);
_id = c.SelectSingleNode("ID").InnerText;
_name = c.SelectSingleNode("Name").InnerText;
_sourceFolder = c.SelectSingleNode("SourceFolder").InnerText;
if (_sourceFolder.Substring(_sourceFolder.Length - 1) != @"\")
_sourceFolder += @"\";
_targetFolder = c.SelectSingleNode("TargetFolder").InnerText;
if (_targetFolder.Substring(_targetFolder.Length - 1) != @"\")
_targetFolder += @"\";
}
#region 属性
private string _id = "";
private string _name = "";
private string _sourceFolder = "";
private string _targetFolder = "";
private bool _enabled = true;
public string ID
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string SourceFolder
{
get { return _sourceFolder; }
set { _sourceFolder = value; }
}
public string TargetFolder
{
get { return _targetFolder; }
set { _targetFolder = value; }
}
public bool Enabled
{
get { return _enabled; }
set { _enabled = value; }
}
#endregion
}
第二步, 需要继承IConfigurationSectionHandler接口
public class ConvertCfgHandler : IConfigurationSectionHandler
{
public ConvertCfgHandler()
{
}
#region IConfigurationSectionHandler Members
public object Create(object parent, object configContext, XmlNode section)
{
List
foreach(XmlNode company in section.SelectNodes("//Company"))
{
CompanySection _company = new CompanySection(company);
if(_company.Enabled)
_list.Add(_company);
}
return _list;
}
#endregion
}
第三步,读取配置项
public class CompanyConfig
{
///
/// 获取配置文件中的公司信息
///
///
public static List
{
return (List
}
}
第四步,使用配置内容
static void Main()
{
private List
foreach(CompanySection company in _companyList)
{
//处理代码
}
}