读取Web.config文件中的配置信息类
using System;
using System.Web;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Xml;
namespace CommHelper
{
public class AppConfig
{
/// <summary>
/// 获得配置属性的bool值
/// </summary>
/// <param name="key"></param>
/// <returns>[True/False]</returns>
public static bool GetBool(string key)
{
bool isBool = false;
try
{
isBool = Convert.ToBoolean(ConfigurationManager.AppSettings[key]);
}
catch {
}
return isBool;
}
/// <summary>
/// 获得配置属性的Int值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static int GetInt(string key)
{
int iValue = -1;
try
{
iValue = Convert.ToInt32(ConfigurationManager.AppSettings[key]);
}
catch { }
return iValue;
}
/// <summary>
/// 获得配置属性的string值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetString(string key)
{
return Convert.ToString(ConfigurationManager.AppSettings[key]);
}
/// <summary>
/// 获得配置属性的Int值
/// </summary>
/// <param name="key"></param>
/// <param name="name"></param>
/// <returns></returns>
public static int GetInt(string key, string name)
{
string str = GetString(key, name);
if (str != null)
{
return Convert.ToInt32(str);
}
return -99999;
}
/// <summary>
/// 获得配置属性的string值
/// </summary>
/// <param name="key"></param>
/// <param name="name"></param>
/// <returns></returns>
public static string GetString(string key, string name)
{
XmlDocument document = new XmlDocument();
document.Load(HttpContext.Current.Server.MapPath("/web.config"));
XmlElement element = (XmlElement)document.SelectSingleNode(string.Format("/configuration/extendSettings/add[@key='{0}']", key));
if (element != null)
{
return element.GetAttribute(name);
}
return null;
}
[Obsolete("This method is obsolete, it has been replaced by GetString method.", true)]
public static string ReadAppSetting(string key)
{
return ConfigurationManager.AppSettings[key];
}
}
}