增删改查(Json版)
class JsonFileHelper
{
// /// <summary>
// /// 创建文件Json文件
// /// </summary>
// /// <param name="jsonName">根目录的相对途径包含文件名</param>
//public JsonFileHelper(string jsonName = "appsettings", string _path = "appsettings.json")
//{
// if (!jsonName.EndsWith(".json"))
// {
// _path = $"{jsonName}.json";
// }
// else
// {
// _path = jsonName;
// }
// if (!File.Exists(_path))
// {//不存在 创建一个json文件
// File.WriteAllText(_path, "{}");
// }
//}
/// <summary>
/// 读取Json返回实体对象
/// </summary>
/// <returns></returns>
public static T Read<T>() => Read<T>("");
/// <summary>
/// 根据节点读取Json返回实体对象
/// </summary>
/// <param name="section">根节点</param>
/// <returns></returns>
public static T Read<T>(string section, string _path = "appsettings.json")
{
try
{
using (StreamReader file = new StreamReader(_path))
using (JsonTextReader reader = new JsonTextReader(file))
{
JToken secJt = JToken.ReadFrom(reader);
if (!string.IsNullOrWhiteSpace(section))
{//jObj[section].SelectToken("address").SelectToken("name")
string[] nodes = section.Split(':');
foreach (string node in nodes)
{
if (node.StartsWith("[") && node.EndsWith("]"))
{
int tempi = 0;
if (int.TryParse(node.Trim('[').Trim(']'), out tempi))
{
secJt = secJt[tempi];
}
}
else
{
secJt = secJt[node];
}
}
if (secJt != null)
{
return JsonConvert.DeserializeObject<T>(secJt.ToString());
}
}
else
{
return JsonConvert.DeserializeObject<T>(secJt.ToString());
}
}
}
catch (Exception ex)
{
throw ex;
}
return default(T);
}
/// <summary>
/// 读取Json返回集合
/// </summary>
/// <returns></returns>
public static List<T> ReadList<T>() => ReadList<T>("");
/// <summary>
/// 根据节点读取Json返回集合
/// </summary>
/// <param name="section">根节点</param>
/// <returns></returns>
public static List<T> ReadList<T>(string section, string _path = "appsettings.json")
{
try
{
using (StreamReader file = new StreamReader(_path))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
JToken secJt = JToken.ReadFrom(reader);
if (!string.IsNullOrWhiteSpace(section))
{
string[] nodes = section.Split(':');
foreach (string node in nodes)
{
secJt = secJt[node];
}
if (secJt != null)
{
return JsonConvert.DeserializeObject<List<T>>(secJt.ToString());
}
}
else
{
return JsonConvert.DeserializeObject<List<T>>(section.ToString());
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return default(List<T>);
}
/// <summary>
/// 写入文件
/// </summary>
/// <typeparam name="T">自定义对象</typeparam>
/// <param name="t"></param>
public static bool Write<T>(T t) => Write("", t);
/// <summary>
/// 写入指定section文件
/// </summary>
/// <typeparam name="T">自定义对象</typeparam>
/// <param name="t"></param>
public static bool Write<T>(string section, T t, string _path = "appsettings.json")
{
try
{
JObject jObj;
string json = JsonConvert.SerializeObject(t);
if (string.IsNullOrWhiteSpace(section))
{
jObj = JObject.Parse(json);
}
else
{
using (StreamReader file = new StreamReader(_path))
using (JsonTextReader reader = new JsonTextReader(file))
{
try
{
jObj = (JObject)JToken.ReadFrom(reader);
jObj[section] = JObject.Parse(json);
}
catch (Exception ex)
{
jObj = JObject.Parse(json);
}
}
}
using (StreamWriter writer = new StreamWriter(_path))
{
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer)
{
Formatting = Formatting.Indented,//格式化缩进
Indentation = 4, //缩进四个字符
IndentChar = ' ' //缩进的字符是空格
})
{
jObj.WriteTo(jsonWriter);
return true;
}
}
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 删除或修改 单个节点
/// </summary>
/// <param name="section">节点途径 格式为A:B:C 如果节点带数组格式 A:[0]:C 数组用中括号</param>
/// <param name="isRemove">是删除还是修改</param>
/// <param name="value">修改节点的内容</param>
/// <param name="isNum">修改内容类型 数据:true 字符串:false</param>
private static bool JTokenHander(string section, bool isRemove, string value, bool isNum, string _path = "appsettings.json")
{
try
{
JToken jObj;
using (StreamReader file = new StreamReader(_path))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
jObj = JToken.ReadFrom(reader);
string[] nodes = section.Split(':');
JToken tempToken = jObj;
if (nodes != null && nodes.Length > 0)
{
foreach (string node in nodes)
{
if (node != null)
{
if (node.StartsWith("[") && node.EndsWith("]"))
{
int tempi = 0;
if (int.TryParse(node.Trim('[').Trim(']'), out tempi))
{
tempToken = tempToken[tempi];
}
}
else
{
tempToken = tempToken[node];
}
}
else
{
break;
}
}
}
if (tempToken != null)
{
if (isRemove)
{
if (tempToken.HasValues)
tempToken.Remove();
else
tempToken.Parent.Remove();
}
else
{
JToken token;
if (isNum)
{
if (value.Contains("."))
{
double tempd;
double.TryParse(value, out tempd);
token = tempd;
}
else
{
int tempi = 0;
int.TryParse(value, out tempi);
token = tempi;
}
}
else
{
token = value;
}
tempToken.Replace(token);//改
}
}
}
}
using (StreamWriter writer = new StreamWriter(_path))
{
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer)
{
Formatting = Formatting.Indented,//格式化缩进
Indentation = 4, //缩进四个字符
IndentChar = ' ' //缩进的字符是空格
})
{
jObj.WriteTo(jsonWriter);
return true;
}
}
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 添加/修改 单个节点
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="keyValuePairs"></param>
/// <param name="isTX">添加:true,修改:false</param>
/// <param name="isT">数据是否为0</param>
/// <param name="_path"></param>
/// <returns></returns>
public static bool JTokenHanderUpdate<T>(Dictionary<string, T> keyValuePairs, bool isTX = false, bool isT = false, string _path = "appsettings.json")
{
try
{
JToken jObj;
using (StreamReader file = new StreamReader(_path))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
jObj = JToken.ReadFrom(reader);
string[] nodes = keyValuePairs.Keys.FirstOrDefault().ToString().Split(':');
JToken tempToken = jObj;
foreach (string node in nodes)
{
if (node != null)
{
if (node.StartsWith("[") && node.EndsWith("]"))
{
int tempi = 0;
if (int.TryParse(node.Trim('[').Trim(']'), out tempi))
{
if (tempi == -1)
{
isT = true;
break;
}
else
{
tempToken = tempToken[tempi];
}
}
}
else
{
tempToken = tempToken[node];
}
}
else
{
break;
}
}
if (tempToken != null)
{
JToken token;
if (isTX)
{
if (isT)
{
dynamic requests = JsonConvert.SerializeObject(keyValuePairs.Values);
dynamic request = JsonConvert.DeserializeObject(requests);
token = request;
tempToken.Replace(token);//添
}
else
{
dynamic requests = JsonConvert.SerializeObject(keyValuePairs.Values.FirstOrDefault());
dynamic request = JsonConvert.DeserializeObject(requests);
token = request;
tempToken.AddAfterSelf(token);//添
}
}
else
{
dynamic requests = JsonConvert.SerializeObject(keyValuePairs.Values.FirstOrDefault());
dynamic request = JsonConvert.DeserializeObject(requests);
token = request;
tempToken.Replace(token);//改
}
}
}
}
using (StreamWriter writer = new StreamWriter(_path))
{
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer)
{
Formatting = Formatting.Indented,//格式化缩进
Indentation = 4, //缩进四个字符
IndentChar = ' ' //缩进的字符是空格
})
{
jObj.WriteTo(jsonWriter);
return true;
}
}
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 删除指定节点
/// </summary>
/// <param name="section">节点途径 格式为A:B:C 如果节点带数组格式 A:[0]:C 数组用中括号</param>
public static bool Remove(string section)
{
return JTokenHander(section, true, "", false);
}
/// <summary>
/// 修改指定节点内容
/// </summary>
/// <param name="section">节点途径 格式为A:B:C 如果节点带数组格式 A:[0]:C 数组用中括号</param>
/// <param name="value">修改节点的内容</param>
/// <param name="isNum">修改内容类型 数据:true 字符串:false</param>
public static bool Update(string section, string value)
{
return JTokenHander(section, false, value, false);
}
/// <summary>
/// 读取节点内容
/// </summary>
/// <param name="section">节点途径 格式为A:B:C 如果节点带数组格式 A:[0]:C 数组用中括号</param>
/// <returns></returns>
public static string Read(string section, string _path = "appsettings.json")
{
try
{
JToken jObj;
using (StreamReader file = new StreamReader(_path))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
jObj = JToken.ReadFrom(reader);
string[] nodes = section.Split(':');
JToken tempToken = jObj;
if (nodes != null && nodes.Length > 0)
{
foreach (string node in nodes)
{
if (node != null)
{
if (node.StartsWith("[") && node.EndsWith("]"))
{
int tempi = 0;
if (int.TryParse(node.Trim('[').Trim(']'), out tempi))
{
tempToken = tempToken[tempi];
}
}
else
{
tempToken = tempToken[node];
}
}
else
{
break;
}
}
}
if (tempToken != null)
{
return tempToken.ToString();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return "";
}
}