①NuGet安装如下两个:
Microsoft.Extensions.Configuration;
Microsoft.Extensions.Configuration.Json;
②ConfigHelper类(类名随意):
using Microsoft.Extensions.Configuration;namespace DataConvert.APP
{public class ConfigHelper{//读取配置文件:appsettings//1.Microsoft.Extensions.Configuration;//2.Microsoft.Extensions.Configuration.Json; public static string GetConfig(string key){var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); //默认读取:当前运行目录IConfigurationRoot configuration = builder.Build();string configValue = configuration.GetSection(key).Value;return configValue;}}
}
③appsettings.json文件:
{//数据库连接字符串:"ConnectionString": {"SqlServer": "server=.;database=test_DB;uid=sa;pwd=123456;", //我的电脑},//其他设置"TaskDelay": 900000, //延时,单位:毫秒
}
④调用config配置:
public string SqlServer = ConfigHelper.GetConfig("ConnectionString:SqlServer");//ConnectionString节点下的SqlServer子节点值public int TaskDelay = Convert.ToInt32(ConfigHelper.GetConfig("TaskDelay"));//节点TaskDelay的值