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
}
}
JsonFiler.cs
最新推荐文章于 2024-01-24 22:33:04 发布