WinForm 抛弃 System.Configuration

本文探讨了在.NET中使用System.Configuration与自定义XML解析器处理复杂配置文件的方法。作者尝试利用ConfigurationElementCollection读取特定格式的配置信息未果,转而采用泛型反射方式实现。文中提供了一个通用类AppConfigurationManage,可通过XPath灵活选取节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写Web程序的时候程序配置使用System.Configuration,感觉很方便。当然了没有使用ConfigurationElementCollection

 

经过一天的努力也没有完成我的功能:

 

读取下面的配置文件使用  ConfigurationElementCollection,整整一天也没有成功。

 

<CommunicateSettings>
  <Communicate name="test">
<Appender name="AdoNetAppender1" type="AdoNetAppender.AdoNetAppender" dll="AdoNetAppender1.dll">
<connectionString value="aaaa" />
<commandText value="bbbb" />
</Appender>
<Analysis name="AutomaticRain" type="AutomaticRain.RainAnalysis" dll="AutomaticRain.dll">
</Analysis>
</Communicate>
 <Communicate name="test2">
<Appender name="AdoNetAppender2" type="AdoNetAppender.AdoNetAppender" dll="AdoNetAppender2.dll">
<connectionString value="aaaa" />
<commandText value="bbbb" />
</Appender>
<Analysis name="AutomaticRain" type="AutomaticRain.RainAnalysis" dll="AutomaticRain.dll">
</Analysis>
</Communicate>
</CommunicateSettings>

 

他只能读取下面的格式


 <CommunicateSettings>
  <Communicate name="test1" type="HongDian.GprsDTU" dll="HongDian.dll" />
 <Communicate name="test2" type="HongDian.GprsDTU" dll="HongDian.dll" />
</CommunicateSettings>

 

无法只能使用原先的类库实现功能。

 

使用泛型反射的方法来实现。类似的代码如下:

public class AppConfigurationManage<T> where T:new()
{
public static IList<T> GetObjectList(string node)
{
IList<T> objectList = new List<T>();

XmlDocument xmldoc = new XmlDocument();

if (File.Exists(XMLConfig.XmlFileName))
{
xmldoc.Load(XMLConfig.XmlFileName);

string tempString = string.Format("/configuration/{0}", node);

XmlNodeList nodeList = xmldoc.SelectNodes(tempString);

Type type;
PropertyInfo propertyInfo;

for(int i = 0; i < nodeList.Count; i++)
{
T model = new T();
type = model.GetType();

for (int j = 0; j < nodeList[i].Attributes.Count; j++)
{
propertyInfo = type.GetProperty(nodeList[i].Attributes[j].Name);

if (propertyInfo != null)
{
propertyInfo.SetValue(model, nodeList[i].Attributes[j].Value, null);
}
}

objectList.Add(model);
}
}
xmldoc = null;

return objectList;
}
}

 

调用方法:

IList<Config.Communicate> objectList = ChangHong.Configuration.AppConfigurationManage<Config.Communicate>.GetObjectList(@"CommunicateSettings/Communicate/Appender"); //此处的参数使用XPATH 语法选择非常灵活

 

另外,哪位大佬有时间或者有类似的项目能读取System.Configuration!

不知道System.Configuration与直接使用XmlDocument性能如何!

希望不惜赐教!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值