当前位置: 首页 > 工具软件 > jtoken > 使用案例 >

本地缓存 - JToken

楚天宇
2023-12-01

废话少说,先甩代码。。。

using System;
using System.Net;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Newtonsoft.Json.Linq;

namespace Camew
{
    /// <summary>
    /// 设置管理
    /// </summary>
    public class SettingManager
    {
        JToken _model = null;

        /// <summary>
        /// 构造设置管理器
        /// </summary>
        /// <param name="path">设置在本地保存的路径</param>
        /// <param name="autoSave">是否自动保存</param>
        public SettingManager(string path, bool autoSave = true)
        {
            this.Path = path;
            this.AutoSave = autoSave;
        }

        public string Path
        {
            get;
            private set;
        }

        public bool AutoSave
        {
            get;
            private set;
        }

        /// <summary>
        /// 获取指定路径的模型
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        JToken GetModel(params string[] path)
        {
            lock (this)
            {
                if (_model == null)
                {
                    InitSettingModel();
                }

                JToken model = _model;
                if (path == null)
                    return model;
                foreach (string p in path)
                {
                    JToken subModel = model[p];
                    if (subModel == null)
                    {
                        subModel = new JObject();
                        model[p] = subModel;
                    }
                    model = subModel;
                }
                return model;
            }
        }

        /// <summary>
        /// 获取指定的属性值
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public string GetValue(string key, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                return dataModel.GetValue(key);
            }
        }

        /// <summary>
        /// 获取指定的属性值列表
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public List<string> GetValues(string key, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                JArray jr = dataModel[key] as JArray;
                if (jr == null)
                    return null;
                return jr.Select(x => x.ToString()).ToList();
            }
        }

        /// <summary>
        /// 获取指定的属性值:Bool
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public bool GetBoolValue(string key, bool defaultValue, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                return dataModel.GetBoolValue(key, defaultValue).Value;
            }
        }

        /// <summary>
        /// 获取指定的属性值列表:Bool
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public List<bool> GetBoolValues(string key, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                JArray jr = dataModel[key] as JArray;
                if (jr == null)
                    return null;
                return jr.Select(x => (bool)x).ToList();
            }
        }

        /// <summary>
        /// 获取指定的属性值:Int
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public int GetIntValue(string key, int defaultValue, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                return dataModel.GetIntValue(key, defaultValue).Value;
            }
        }

        /// <summary>
        /// 获取指定的属性值列表:Int
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public List<int> GetIntValues(string key, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                JArray jr = dataModel[key] as JArray;
                if (jr == null)
                    return null;
                return jr.Select(x => (int)x).ToList();
            }
        }

        /// <summary>
        /// 获取指定的属性值:Float
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public float GetFloatValue(string key, float defaultValue, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                return dataModel.GetFloatValue(key, defaultValue).Value;
            }
        }

        /// <summary>
        /// 获取指定的属性值列表:Float
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public List<float> GetFloatValues(string key, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                JArray jr = dataModel[key] as JArray;
                if (jr == null)
                    return null;
                return jr.Select(x => (float)x).ToList();
            }
        }

        /// <summary>
        /// 获取指定的属性值:DateTime
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public DateTime GetDateTimeValue(string key, DateTime defaultValue, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                return dataModel.GetDateTimeValue(key, defaultValue).Value;
            }
        }

        /// <summary>
        /// 获取指定的属性值列表:DateTime
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public List<DateTime> GetDateTimeValues(string key, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                JArray jr = dataModel[key] as JArray;
                if (jr == null)
                    return null;
                return jr.Select(x => (DateTime)x).ToList();
            }
        }



        /// <summary>
        /// 设置指定的属性值
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="value">值</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public void SetValue(string key, object value, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                if (value != null)
                    dataModel[key] = JToken.FromObject(value);
                else if (dataModel[key] != null)
                {
                    dataModel[key].Remove();
                }
                if (AutoSave)
                    Save();
            }
        }

        /// <summary>
        /// 设置指定的属性值
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="values">值</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public void SetValues(string key, IEnumerable values, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                if (values != null)
                {
                    JArray jr = new JArray();
                    foreach (object d in values)
                    {
                        jr.Add(d);
                    }
                    dataModel[key] = jr;
                }
                else if (dataModel[key] != null)
                {
                    dataModel[key].Remove();
                }
                if (AutoSave)
                    Save();
            }
        }

        /// <summary>
        /// 移除某个属性
        /// </summary>
        /// <param name="key"></param>
        /// <param name="path"></param>
        public void RemoveValue(string key, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                if (dataModel[key] != null)
                    dataModel[key].Remove();
                if (AutoSave)
                    Save();
            }
        }


        void CreateFolder(string path)
        {
            int index = path.LastIndexOf("\\");
            if (index == -1)
                return;
            if (index != path.Length - 1)
                path = path.Substring(0, index + 1);
            if (Directory.Exists(path))
                return;
            Directory.CreateDirectory(path);
        }


        void InitSettingModel()
        {
            if (File.Exists(Path))
            {

                try
                {
                    _model = JToken.Parse(File.ReadAllText(Path));
                }
                catch
                {
                    File.Delete(Path);
                    _model = new JObject();
                }

            }
            else
            {
                _model = new JObject();
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public void Save()
        {
            Action action = InnerSave;
            action.BeginInvoke(null, null);
        }

        void InnerSave()
        {
            lock (this)
            {
                CreateFolder(Path);
                FileSystem.SaveSafeFileForString(this.ToString(), Path);
            }
        }

        public override string ToString()
        {
            return GetModel().ToString();
        }
    }
}


存储时按照键值(key, value)按照路径存储的,可以类比XML结构。

1.实例化
    public SettingManager Settings
        {
            get;
            private set;
        }

2.设置存储路径和存储文件名
   string appSettingFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + BasicInfo.CompanyInnerName + "\\" + BasicInfo.AppCode + "\\";
            if (!Directory.Exists(appSettingFolder))
                Directory.CreateDirectory(appSettingFolder);
            this.AppSettingFolder = appSettingFolder;
            DevTools.DefaultNoteFolderPath = this.AppSettingFolder;//设置日志存储路径
            this.Settings = new SettingManager(AppSettingFolder + "Settings.st");    

一般本地缓存和日志基本放在一个级目录下;
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)是获取本地“我的文档”文件夹
3.写入内容

可以写入不同类型的值,int,string,bool等等基本类型
Settings.SetValue(key, show.ToString(), path);

上面代码实现写入show这个string类型的字符串, path是存储路径,key是标志,类比XML中的<key,value>.
4.读取内容
 string vv = CoreApp.CurApp.CurSession.Settings.GetValue(key, path);

读取内容通过key值和路径获取内容。
5.支持列表List存储
 /// <summary>
        /// 设置指定的属性值
        /// </summary>
        /// <param name="key">属性名字</param>
        /// <param name="values">值</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public void SetValues(string key, IEnumerable values, params string[] path)
        {
            lock (this)
            {
                JToken dataModel = GetModel(path);
                if (values != null)
                {
                    JArray jr = new JArray();
                    foreach (object d in values)
                    {
                        jr.Add(d);
                    }
                    dataModel[key] = jr;
                }
                else if (dataModel[key] != null)
                {
                    dataModel[key].Remove();
                }
                if (AutoSave)
                    Save();
            }
        }

设置存储values为 IEnumerable 类型支持多种类型

6.注意:这里要引用 Newtonsoft.Json.Linq
关于 Newtonsoft.Json 

Newtonsoft.Json简介和应用

 类似资料: