config.json 文件内容如下 {"Data": {"DefaultConnection": {"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Books;Trusted_Connection=True;"}},"Appsettings": { "Name": "XiaoLi", "Date": "2020-04-18", "age": "20" }, "url":"htt
config.json 文件内容如下
{ "Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Books;Trusted_Connection=True;" } }, "Appsettings": { "Name": "XiaoLi", "Date": "2020-04-18", "age": "20" }, "url":"https://blog.csdn.net/weixin_42686768" }
设置配置文件
项目config.json文件右键——属性——将“复制到输出目录”项的值改为“始终复制”
添加引用
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using System.IO; public static string GetConnectionString(string value) { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json"); //var configurationBuilder = new ConfigurationBuilder() // .Add(new JsonConfigurationSource { Path = "config.json", ReloadOnChange = true }); IConfiguration config = configurationBuilder.Build(); string connectionString = config[value]; return connectionString; } // 1、获取 ConnectionString 对应的字符串 va = "Data:DefaultConnection:ConnectionString"; // 2、获取 Name 对应的字符串 va = "Appsettings:Name"; // 3、获取 url 对应的字符串 va = "url"; GetConnectionString(va)
到此这篇关于vs C#项目读取JSON配置文件的文章就介绍到这了,更多相关C#读取JSON配置文件内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!