vs 中C#项目读取JSON配置文件的方法
程序员文章站
2022-06-17 22:13:50
config.json 文件内容如下{"data": {"defaultconnection": {"connectionstring": "server=(localdb)\\mssqllocald...
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配置文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!