C#自定讀取配置文件類實例
更新時間:2015年03月25日 14:44:47 作者:lele
這篇文章主要介紹了C#自定讀取配置文件類,實例分析了C#讀取配置文件的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#自定讀取配置文件類。分享給大家供大家參考。具體如下:
這個C#類定義了讀取AppSettings的配置文件的常用方法,通過這個類可以很容易從AppSettings配置文件讀取字符串、數(shù)字、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#實現(xiàn)操作windows系統(tǒng)服務(service)的方法
這篇文章主要介紹了C#實現(xiàn)操作windows系統(tǒng)服務(service)的方法,可實現(xiàn)系統(tǒng)服務的啟動和停止功能,非常具有實用價值,需要的朋友可以參考下2015-04-04
C# DataTable中查詢指定字段名稱的數(shù)據(jù)
這篇文章主要介紹了C# DataTable中查詢指定字段名稱的數(shù)據(jù),本文直接給出實例代碼,簡單易懂,需要的朋友可以參考下2015-06-06
詳解如何使用BenchmarkDotNet對.NET代碼進行性能基準測試
BenchmarkDotNet是一個基于.NET開源、功能全面、易于使用的性能基準測試框架,這篇文章就來和小編一起學習一下如何使用BenchmarkDotNet對.NET代碼進行性能基準測試吧2024-12-12

