c# Config 配置文件帮助类
public class ConfigHelper
{
#region 获取指定目录 AppSettings 配置文件值
/// <summary>
/// 获取指定目录 AppSettings 配置文件值
/// </summary>
/// <param name="key"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetAppSettings(string key, string fileName = "config/App.config")
{
var value = "";
if (string.IsNullOrEmpty(fileName))
{
value = ConfigurationManager.AppSettings[key].ToString();
}
else
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = System.AppDomain.CurrentDomain.BaseDirectory + fileName;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
{
value = config.AppSettings.Settings[key].Value;
}
}
return value;
}
#endregion
#region 获取指定目录 ConnectionStrings 配置文件值
/// <summary>
/// 获取指定目录 ConnectionStrings 配置文件值
/// </summary>
/// <param name="key"></param>
/// <param name="fileName">config/app.config</param>
/// <returns></returns>
public static string GetConnectionStrings(string key, string fileName = "")
{
var value = "";
if (string.IsNullOrEmpty(fileName))
{
value = ConfigurationManager.ConnectionStrings[key].ConnectionString;
}
else
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = System.AppDomain.CurrentDomain.BaseDirectory + fileName;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
if (config.ConnectionStrings.ConnectionStrings[key] != null)
{
value = config.ConnectionStrings.ConnectionStrings[key].ConnectionString;
}
}
return value;
}
#endregion
}