欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#自定读取配置文件类实例

时间:2021-04-20 08:59:06|栏目:.NET代码|点击:

本文实例讲述了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#检查foreach判读是否为null的方法

栏    目:.NET代码

下一篇:c# 实现位图算法(BitMap)

本文标题:C#自定读取配置文件类实例

本文地址:http://www.codeinn.net/misctech/105355.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有