nuget
Microsoft.Extensions.Configuration;
Microsoft.Extensions.Configuration.Json;
Newtonsoft.Json;
Newtonsoft.Json.Linq;
///
/// Json文件读写
/// 引用Newtonsoft.Json
///
public class JsonFileHelper
{
//注意:section为根节点
private string _jsonName;
private string _path;
private IConfiguration Configuration { get; set; }
public JsonFileHelper(string jsonName)
{
_jsonName = jsonName;
if (!jsonName.EndsWith(".json"))
_path = $"{jsonName}.json";
else
_path = jsonName;
//ReloadOnChange = true 当*.json文件被修改时重新加载
Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = _path, ReloadOnChange = true, Optional = true })
.Build();
}
///
/// 读取Json返回实体对象
///
///
public T Read() => Read("");
///
/// 根据节点读取Json返回实体对象
///
///
public T Read(string section)
{
try
{
using (var file = new StreamReader(_path))
using (var reader = new JsonTextReader(file))
{
var jObj = (JObject)JToken.ReadFrom(reader);
if (!string.IsNullOrWhiteSpace(section))
{