C#配置文件Section节点处理总结
本文实例总结了C#配置文件Section节点处理方法。分享给大家供大家参考。具体如下:
很多时候在项目开发中,我们都需要用配置文件来存储一些关于程序配置信息,这时候你可以选择INI或者app.config来存储,这里对此总结一下:
配置文件示例如下:
<?xmlversion="1.0"encoding="utf-8"?> <configuration> <configSections> <sectionGroupname="module"> <sectionname="appSettings"type="System.Configuration.NameValueFileSectionHandler"/> </sectionGroup> </configSections> <module> <appSettings> <!--谷歌地图--> <addkey="Googlemap"value="1"/> <!--箱实时状态信息汇总--> <addkey="Cab_rt"value="1"/> </appSettings> </module> </configuration>
操作代码如下:
usingSystem; usingSystem.Collections.Specialized; usingSystem.Configuration;
namespaceConsoleApplication38 { classProgram { staticvoidMain(string[]args) { try { SectionToolV2_sectionHelper=newSectionToolV2("module/appSettings"); Console.WriteLine(_sectionHelper.GetValue("Googlemap")); Console.WriteLine(_sectionHelper.ContainKey("YanZhiwei")); } catch(Exceptionex) { Console.WriteLine(ex.Message); } finally { Console.ReadLine(); } } } classSectionToolV2 { NameValueCollectionModulSettings=null; ///<summary> ///构造函数 ///</summary> ///<paramname="sectionName">section名称</param> publicSectionToolV2(stringsectionName) { ModulSettings=ConfigurationManager.GetSection(sectionName)asNameValueCollection; } ///<summary> ///是否包含该Section ///</summary> ///<returns></returns> publicboolContainSection() { return!(ModulSettings==null); } ///<summary> ///Section是否包含Key ///</summary> ///<paramname="key">键</param> ///<returns>值</returns> publicboolContainKey(stringkey) { if(ContainSection()) { return!(ModulSettings[key]==null); } returnfalse; } ///<summary> ///根据键获取值 ///</summary> ///<paramname="Key">键</param> ///<returns>当不存在键的时候,返回string.Empty</returns> publicstringGetValue(stringKey) { string_value=string.Empty; if(ContainKey(Key)) { _value=ModulSettings[Key]; } return_value; } } }