
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace SlnMesnac.Config
{
    public class AppsettingsConfig
    {
        private IConfiguration _configuration;

        public AppsettingsConfig()
        {
            // 创建ConfigurationBuilder对象
            var builder = new ConfigurationBuilder();

            // 设置appsettings.json文件的路径
            builder.SetBasePath(System.IO.Directory.GetCurrentDirectory()) // 如果appsettings.json不在当前目录下，需要修改路径
                   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            // 构建IConfiguration对象
            _configuration = builder.Build();
        }
        public string ReadAppSettings(string session)
        {
            // 读取配置信息
            //_configuration.GetSection("AppConfig:OKCount").Value.ToString();
            return _configuration.GetSection(session).Value.ToString();
        }
        public bool WriteAppSettings(string session,string key, string value)
        {
            string contentPath = System.IO.Directory.GetCurrentDirectory() + @"\";   //项目根目录
            var filePath = contentPath + "appsettings.json";
            JObject jsonObject;
            using (StreamReader file = new StreamReader(filePath))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                jsonObject = (JObject)JToken.ReadFrom(reader);
                jsonObject[session][key] = value;
            }

            using (var writer = new StreamWriter(filePath))
            using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
            {
                jsonObject.WriteTo(jsonwriter);
            }

            return true;
        }


    }
}
