C#自定讀取配置文件類

pdkie 9年前發布 | 1K 次閱讀 C#

這個C#類定義了讀取AppSettings的配置文件的常用方法,通過這個類可以很容易從AppSettings配置文件讀取字符串、數字、bool類型的字段信息。

登錄
注冊
訂閱RSS
網站地圖
腳本分享網
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;
    }
}

}</pre>

 本文由用戶 pdkie 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!