栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

C# – 如何在控制台应用程序中添加和读取 appsetting.json 文件

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C# – 如何在控制台应用程序中添加和读取 appsetting.json 文件

在这篇文章中,我们将了解如何在 .NET Core 控制台应用程序中添加和读取 appsettings.json 文件。
我们打开 Visual Studio 并创建一个名为“ TestJson ”的控制台应用程序 (.NET Core) 项目:

现在,我们添加一个名为“Parameters.json”的文件,我们将在其中存储一个 DB 的连接字符串和两个名为 ValueABC 和 ValueDEF 的参数:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DbConnection": "ExampleTestConnection"
  },
  "Parameter": {
    "ValueABC": "TestValue_ABC",
    "ValueDEF": "TestValue_DEF"
  }
}


重要提示:我们必须将文件的属性“复制到输出目录”设置为:“如果较新则复制”:

现在,为了读取 Parameters.json 文件,我们必须使用 NuGet 包添加三个库:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json

最后,我们修改 Program.cs 以读取 appsetting 文件:

using Microsoft.Extensions.Configuration;
using System;
using System.IO;
 
namespace TestJson
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting reading file .json");
 
            Console.WriteLine($"ConnectioString: {GetDbConnection()}");
 
            Console.WriteLine($"The parameters are: {GetParameters()}");
 
            Console.ReadLine();
        }
 
        private static string GetDbConnection()
        {
            var builder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("Parameters.json", optional: true, reloadOnChange: true);
 
            string strConnection = builder.Build().GetConnectionString("DbConnection");
 
            return strConnection;
        }
 
        private static string GetParameters()
        {
            var builder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("Parameters.json", optional: true, reloadOnChange: true);
 
            var val1 = builder.Build().GetSection("Parameter").GetSection("ValueABC").Value;
            var val2 = builder.Build().GetSection("Parameter").GetSection("ValueDEF").Value;
 
            return $"The values of parameters are: {val1} and {val2}";
        }
    }
}

如果我们运行应用程序,这将是结果:


 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/983163.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号