netframework读取appsettings.json
- 人工智能
- 2025-09-10 23:21:02

AppSettingsHelper:
using Newtonsoft.Json.Linq; using System; using System.IO; public class AppSettingsHelper { private static JObject _appSettings; static AppSettingsHelper() { try { // 获取 appsettings.json 文件的路径 var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json"); // 检查文件是否存在 if (!File.Exists(filePath)) { throw new FileNotFoundException("appsettings.json file not found!"); } // 读取文件内容并解析为 JObject var json = File.ReadAllText(filePath); _appSettings = JObject.Parse(json); } catch (Exception ex) { throw new Exception($"Error loading appsettings.json: {ex.Message}"); } } /// <summary> /// 获取指定键的值 /// </summary> /// <param name="keyPath">键路径,例如 "AppSettings:Setting1"</param> /// <param name="defaultValue">默认值(可选)</param> /// <returns>键对应的值,如果键不存在则返回默认值</returns> public static string GetSetting(string keyPath, string defaultValue = null) { if (_appSettings == null) { throw new Exception("appsettings.json is not loaded."); } // 分割键路径 var keys = keyPath.Split(':'); JToken token = _appSettings; // 逐级查找键 foreach (var key in keys) { token = token[key]; if (token == null) { throw new Exception($"Key '{key}' in path '{keyPath}' not found."); } } return token.ToString(); } /// <summary> /// 获取指定键的值并转换为指定类型 /// </summary> /// <typeparam name="T">目标类型</typeparam> /// <param name="keyPath">键路径,例如 "AppSettings:Setting1"</param> /// <param name="defaultValue">默认值(可选)</param> /// <returns>键对应的值,如果键不存在则返回默认值</returns> public static T GetSetting<T>(string keyPath, T defaultValue = default) { if (_appSettings == null) { throw new Exception("appsettings.json is not loaded."); } // 分割键路径 var keys = keyPath.Split(':'); JToken token = _appSettings; // 逐级查找键 foreach (var key in keys) { token = token[key]; if (token == null) { throw new Exception($"Key '{key}' in path '{keyPath}' not found."); } } return token.ToObject<T>(); } }appsettings.json:
{ "ConnectionStrings": { "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" }, "AppSettings": { "Setting1": "Value1", "Setting2": "Value2" } }output:
class Program { static void Main(string[] args) { // 读取字符串类型的配置 var setting1 = AppSettingsHelper.GetSetting("AppSettings:Setting1"); Console.WriteLine($"Setting1: {setting1}"); // 读取连接字符串 var connectionString = AppSettingsHelper.GetSetting("ConnectionStrings:DefaultConnection"); Console.WriteLine($"DefaultConnection: {connectionString}"); // 读取并转换为特定类型(如果需要) var setting2 = AppSettingsHelper.GetSetting<string>("AppSettings:Setting2"); Console.WriteLine($"Setting2: {setting2}"); Console.ReadKey(); } }netframework读取appsettings.json由讯客互联人工智能栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“netframework读取appsettings.json”