.net core 配制文件读取操作
/// <summary> /// 配制文件读取类 /// </summary> public static class ConfigHelper { private static IConfiguration _configuration; static ConfigHelper() { //在当前目录或者根目录中寻找appsettings.json文件 var fileName = "appsettings.json"; var directory = AppContext.BaseDirectory; directory = directory.Replace("\\", "/"); var filePath = $"{directory}/{fileName}"; if (!File.Exists(filePath)) { var length = directory.IndexOf("/bin"); filePath = $"{directory.Substring(0, length)}/{fileName}"; } var builder = new ConfigurationBuilder() .AddJsonFile(filePath, false, true); _configuration = builder.Build(); } /// <summary> /// 获取配制文件节点 /// </summary> /// <param name="key">配制文件路由KEY</param> /// <returns></returns> public static string GetSectionValue(string key) { return _configuration.GetSection(key).Value; } /// <summary> /// 获取配制文件KEY为ConnctionStrings中的KEY值 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetConnctionString(string key) { return _configuration.GetConnectionString($"ConnctionString:{key}"); } /// <summary> /// 获取配制文件中key为AppSetting中的KEY /// </summary> /// <param name="key"></param> /// <returns></returns> public static string AppSetting(string key) { return _configuration.GetSection($"AppSetting:{key}").Value; } }