.net Core命令行,Json配置

本文介绍了如何在.NET Core控制台应用中通过多种方式读取配置信息,包括从命令行参数、内存字典及JSON文件中获取配置,并展示了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建.netCore控制台

NuGet :Microsoft.AspNetCore.All

     static void Main(string[] args)
        {

       var builder = new ConfigurationBuilder() .AddCommandLine(args);//扩展函数 var configuration = builder.Build();//绑定到configuration Console.WriteLine($"name:{configuration["name"]}"); Console.WriteLine($"Age:{configuration["Age"]}"); Console.ReadLine(); }

直接运行没有结果,然后在应用程序参数

输出结果 

另一种方式,给与默认值

      static void Main(string[] args)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                { "name","Zhanglong1"},
                { "Age","Age=22"}
            };

            var builder = new ConfigurationBuilder()
                .AddInMemoryCollection(dic)//默认值
                .AddCommandLine(args);
            var configuration = builder.Build();
            Console.WriteLine($"name:{configuration["name"]}");
            Console.WriteLine($"Age:{configuration["Age"]}");
            Console.ReadLine();
        }

 Json文件配置

控制台中添加.json文件

然后Main方法

 static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("Class.json",false,true);//方法重载,1文件夹2当不存在的时候是否抛异常3当文件改变时是否重新加载配置
            var configuration = builder.Build();
            Console.WriteLine($"ClassNo:{configuration["ClassNo"]}");
            Console.WriteLine($"ClassDesc:{configuration["ClassDesc"]}");
            Console.WriteLine("Students");
            Console.Write($"Name={configuration["Students:0:name"]}");
            Console.WriteLine($"Name={configuration["Students:0:Age"]}");
            Console.Write($"Name={configuration["Students:1:name"]}");
            Console.WriteLine($"Name={configuration["Students:1:Age"]}");
            Console.Write($"Name={configuration["Students:2:name"]}");
            Console.WriteLine($"Name={configuration["Students:2:Age"]}");
            Console.ReadLine();
        }

输出结果:

jsonpatch.com https://dotnetcoretutorials.com/?s=jsonpatch&submit=Search

 

转载于:https://www.cnblogs.com/AnkerZhang/p/8358402.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值