.net core 讀取json文件


核心代碼

  Program.cs:

復制代碼
using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            //添加 json 文件路徑
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            //創建配置根對象
            var configurationRoot = builder.Build();

            //取配置根下的 name 部分
            var nameSection = configurationRoot.GetSection("name");
            //取配置根下的 family 部分
            var familySection = configurationRoot.GetSection("family");
            //取 family 部分下的 mother 部分下的 name 部分
            var motherNameSection = familySection.GetSection("mother").GetSection("name");
            //取 family 部分下的 father 部分下的 age 部分
            var fatherAgeSection = familySection.GetSection("father").GetSection("age");

            //Value 為文本值
            Console.WriteLine($"name: {nameSection.Value}");
            Console.WriteLine($"motherName: {motherNameSection.Value}");
            Console.WriteLine($"fatherAge: {fatherAgeSection.Value}");
            Console.Read();
        }
    }
}

 --------------------------------------------------------

2.

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM