JsonFiler.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using LitJson;

namespace Common
{
    public static class JsonFiler
    {
        #region 公共变量
        public static string Path { get; set; }

        #endregion

        #region 私有常量
        const string SectionName = "section";
        const string KeyName = "key";
        const string ValueName = "value";

        #endregion

        #region 私有结构
        struct KeyData
        {
            public string Section;
            public string Key;
            public string Value;
        }

        #endregion

        #region 公共函数
        public static void Write(string section, string key, string value)
        {
            var jsonData = new JsonData();
            jsonData[SectionName] = section;
            jsonData[KeyName] = key;
            jsonData[ValueName] = value;
            saveJsonData(section, key, jsonData, Path);
        }

        public static string Read(string sectionName, string keyName)
        {
            var fs = getFile(Path);
            var sr = new StreamReader(fs);
            var value = string.Empty;
            var k = new KeyData();
            while (!sr.EndOfStream)
            {
                k = getKeyData(sr.ReadLine());
                if (!k.Section.Equals(sectionName) || !k.Key.Equals(keyName)) continue;
                value = k.Value;
                break;
            }
            fs.Close();
            return value;
        }

        #endregion

        #region 私有函数
        static FileStream getFile(string filePath, FileMode mode = FileMode.Open)
        {
            var path = filePath.Substring(0, filePath.LastIndexOf("/", StringComparison.Ordinal));
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            var file = !File.Exists(filePath) ? new FileStream(filePath, FileMode.Create) : new FileStream(filePath, mode);
            return file;
        }

        static KeyData getKeyData(string source)
        {
            source = source.Trim('{', '}');
            source = source.Replace("\"", string.Empty);
            var k = new KeyData();
            var debris = source.Split(',');
            foreach (var split in debris.Select(t => t.Split(':')))
            {
                switch (split[0])
                {
                    case SectionName:
                        k.Section = split[1];
                        break;
                    case KeyName:
                        k.Key = split[1];
                        break;
                    case ValueName:
                        k.Value = split[1];
                        break;
                }
            }
            return k;
        }

        static void saveJsonData(string sectionName, string keyName, JsonData jsonData, string filePath, FileMode mode = FileMode.Create)
        {
            var dirPath = filePath.Substring(0, filePath.LastIndexOf("/", StringComparison.Ordinal));
            if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
            if (File.Exists(filePath))
            {//文件存在则搜索指定名称json数据串并写入

                //删除匹配section和key的项
                var lines = File.ReadAllLines(filePath).ToList();
                foreach (var line in from l in lines let k = getKeyData(l) where k.Section.Equals(sectionName) && k.Key.Equals(keyName) select l)
                {
                    lines.Remove(line);
                    break;
                }

                //添加新json串
                var jsonLine = jsonData.ToJson();
                lines.Add(jsonLine);

                //保存文件
                var fs = new FileStream(filePath, mode);
                var sb = new StringBuilder();
                foreach (var line in lines) sb.Append(line + "\r\n");//拷贝至可变字符串
                var buff = Encoding.UTF8.GetBytes(sb.ToString());//转换为字节数据
                fs.Write(buff, 0, buff.Length);
                fs.Close();
            }
            else
            {//文件不存在则新建并保存
                var fs = new FileStream(filePath, FileMode.Create);
                var str = jsonData.ToJson() + "\r\n";
                var buff = Encoding.UTF8.GetBytes(str);
                fs.Write(buff, 0, buff.Length);
                fs.Close();
            }
        }

        #endregion

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值