在.Net Framework中,配置文件一般采用的是XML格式的,.NET Framework提供了专门的ConfigurationManager来读取配置文件的内容,.net core中推荐使用json格式的配置文件,那么在.net core中该如何读取json文件呢?
1、在Startup类中读取json配置文件
在Startup加入配置
var configurationBuilder = new ConfigurationBuilder();
var builder = configurationBuilder.AddJsonFile("UploadFile/GetCourts.json", false, true).AddJsonFile("UploadFile/Queryareadatalevelall.json", false, true);
var Courtlist = new Courtlist();
builder.Build().Getp("Courtsmodel").Bind(Courtlist);
services.AddSingleton(Courtlist);
构造函数注入读取
private readonly Courtlist _Courtlist;
private readonly AreaRootobjectlist _AreaRootobjectlist;
public DmsCacheService(
AreaRootobjectlist AreaRootobjectlist,
Courtlist Courtlist,
ILogger<DmsCacheService> logger,
AccessAddressDto accessAddress,
IEasyCachingProvider provider,
IJudgeBannedWordsService judgeBannedWordsService,
IJudgeService judgeService,
IMapper mapper)
{
this.provider = provider;
this.judgeService = judgeService;
this.judgeBannedWordsService = judgeBannedWordsService;
this.mapper = mapper;
this.accessAddress = accessAddress;
this.logger = logger;
_Courtlist = Courtlist;
_AreaRootobjectlist = AreaRootobjectlist;
}
public List<Court> GetCourts()
{
return _Courtlist.Courtlists;
}
2、从硬盘直接读取
定义读取方法
private T GetDataByLocal<T>(string jsonfileName)
{
var res = this.provider.Get<T>(jsonfileName);
if (res.HasValue)
{
return res.Value;
}
var filePath = $"/UploadFile/";
string applicationRoot = AppContext.BaseDirectory;
var provider = new PhysicalFileProvider(applicationRoot);
var completeFilePath = Path.Combine(filePath, jsonfileName);
if (!System.IO.File.Exists(AppContext.BaseDirectory + completeFilePath))
{
throw new Exception("文件不存在");
}
var formFile = provider.GetFileInfo(completeFilePath);
var stream = formFile.CreateReadStream();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding encoding = Encoding.GetEncoding("gb2312");
using var reader = new StreamReader(stream, encoding);
string rs = reader.ReadToEnd();
var result = JsonConvert.DeserializeObject<T>(rs);
this.provider.Set<T>(jsonfileName, result, this.GetExpiredTimeSpan());
return result;
}
传入文件名进行读取
public List<CaseCodeType> GetCaseCodes()
{
return this.GetDataByLocal<List<CaseCodeType>>("GetCaseCodes.json");
}