程序中为了保持灵活性,将一些参数写到配置文件中,方便修改和做到可支持配置。相应的我们必须从配置文件读取相应的配置信息,以下为读取配置文件appseting相应配置key的通用方法,陪讲一些通用的方法写成一个通用的类或者做成一个通用common的dll,方便开发很方便的调用。
public static string GetConfigString(string key)
{
string cacheKey = "AppSettings-" + key;
object obj = DataCache.GetCache(cacheKey);
if (obj == null)
{
try
{
obj = ConfigurationManager.AppSettings[key];
if (obj != null)
{
DataCache.SetCache(cacheKey, obj, DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
}
}
catch
{
}
}
return obj.ToString();
}
public static int GetConfigInt(string key)
{
int result = 0;
string configString = ConfigHelper.GetConfigString(key);
if (configString != null && string.Empty != configString)
{
try
{
result = int.Parse(configString);
}
catch (FormatException)
{
}
}
return result;
}
public static decimal GetConfigDecimal(string key)
{
decimal result = 0m;
string configString = ConfigHelper.GetConfigString(key);
if (configString != null && string.Empty != configString)
{
try
{
result = decimal.Parse(configString);
}
catch (FormatException)
{
}
}
return result;
}
public static bool GetConfigBool(string key)
{
bool result = false;
string configString = ConfigHelper.GetConfigString(key);
if (configString != null && string.Empty != configString)
{
try
{
result = bool.Parse(configString);
}
catch (FormatException)
{
}
}
return result;
}
public sealed class ConfigHelper
{
public static string GetConfigString(string key)
{
string cacheKey = "AppSettings-" + key;
object obj = DataCache.GetCache(cacheKey);
if (obj == null)
{
try
{
obj = ConfigurationManager.AppSettings[key];
if (obj != null)
{
DataCache.SetCache(cacheKey, obj, DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
}
}
catch
{
}
}
return obj.ToString();
}
public static bool GetConfigBool(string key)
{
bool result = false;
string configString = ConfigHelper.GetConfigString(key);
if (configString != null && string.Empty != configString)
{
try
{
result = bool.Parse(configString);
}
catch (FormatException)
{
}
}
return result;
}
public static decimal GetConfigDecimal(string key)
{
decimal result = 0m;
string configString = ConfigHelper.GetConfigString(key);
if (configString != null && string.Empty != configString)
{
try
{
result = decimal.Parse(configString);
}
catch (FormatException)
{
}
}
return result;
}
public static int GetConfigInt(string key)
{
int result = 0;
string configString = ConfigHelper.GetConfigString(key);
if (configString != null && string.Empty != configString)
{
try
{
result = int.Parse(configString);
}
catch (FormatException)
{
}
}
return result;
}
}