当前位置: 首页 > article >正文

netframework 读取appsettings.json

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();
     }
 }


http://www.kler.cn/a/572257.html

相关文章:

  • 【练习】【链表】力扣热题100 160. 相交链表
  • CC++的内存管理
  • 网络安全ctf试题 ctf网络安全大赛真题
  • stm32(hal库)学习笔记-时钟系统
  • BS架构(笔记整理)
  • npm、Yarn 与 pnpm:选择最适合你的包管理工具
  • 【Android】 工具篇:ProxyPin抓包详解---夜神模拟器
  • 突破光学成像局限:全视野光学血管造影技术新进展
  • 深度学习-大白话解释循环神经网络RNN
  • 医药行业哪些招聘管理系统有AI功能?
  • 基于vue3和flask开发的前后端管理系统(一):项目启动准备
  • 鸿蒙5.0实战案例:基于webview拉起自定义键盘
  • 【车规芯片】如何引导时钟树生长方向
  • C#基础及标准控件的使用,附登录案例
  • navicat下载与安装【带布丁】
  • printf 与前置++、后置++、前置--、后置-- 的关系
  • 从ETL到数仓分层:大数据处理的“金字塔”构建之道
  • Ubuntu 20.04下配置VSCode以支持ROS开发
  • 【Git原理与使用二】Git 分支管理
  • 解决git clone下载慢或者超时问题