手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#自定读取配置文件类实例
C#自定读取配置文件类实例
摘要:本文实例讲述了C#自定读取配置文件类。分享给大家供大家参考。具体如下:这个C#类定义了读取AppSettings的配置文件的常用方法,通过这...

本文实例讲述了C#自定读取配置文件类。分享给大家供大家参考。具体如下:

这个C#类定义了读取AppSettings的配置文件的常用方法,通过这个类可以很容易从AppSettings配置文件读取字符串、数字、bool类型的字段信息。

using System; using System.Configuration; namespace DotNet.Utilities { /// <summary> /// web.config操作类 /// </summary> public sealed class ConfigHelper { /// <summary> /// 得到AppSettings中的配置字符串信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetConfigString(string key) { string CacheKey = "AppSettings-" + key; object objModel = DataCache.GetCache(CacheKey); if (objModel == null) { try { objModel = ConfigurationManager.AppSettings[key]; if (objModel != null) { DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(180), TimeSpan.Zero); } } catch { } } return objModel.ToString(); } /// <summary> /// 得到AppSettings中的配置Bool信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool GetConfigBool(string key) { bool result = false; string cfgVal = GetConfigString(key); if(null != cfgVal && string.Empty != cfgVal) { try { result = bool.Parse(cfgVal); } catch(FormatException) { // Ignore format exceptions. } } return result; } /// <summary> /// 得到AppSettings中的配置Decimal信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static decimal GetConfigDecimal(string key) { decimal result = 0; string cfgVal = GetConfigString(key); if(null != cfgVal && string.Empty != cfgVal) { try { result = decimal.Parse(cfgVal); } catch(FormatException) { // Ignore format exceptions. } } return result; } /// <summary> /// 得到AppSettings中的配置int信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public static int GetConfigInt(string key) { int result = 0; string cfgVal = GetConfigString(key); if(null != cfgVal && string.Empty != cfgVal) { try { result = int.Parse(cfgVal); } catch(FormatException) { // Ignore format exceptions. } } return result; } } }

希望本文所述对大家的C#程序设计有所帮助。

【C#自定读取配置文件类实例】相关文章:

C#解析json文件的实现代码

解析C#自定义控件的制作与使用实例的详解

用C#实现启动另一程序的方法实例

读取图片像素的具体实例

c#解压文件的实例方法

C#访问应用程序配置文件的方法

C#中通过API实现的打印类 实例代码

C# Winform 调用系统接口操作 INI 配置文件的代码

c#自定义泛型类的实现

C# 获取程序集版本、文件版本

精品推荐
分类导航