1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using System;
- using System.IO;
- using System.Text;
- namespace MainForm.Common
- {
- public class JsonFileHelper
- {
- /// <summary>
- /// 读取JSON文件
- /// </summary>
- /// <typeparam name="T">返回的类型</typeparam>
- /// <param name="fileName">打开的文件路径</param>
- /// <returns>实体类</returns>
- public static T ReadjsonT<T>(string fileName)
- {
- //using (System.IO.StreamReader file = System.IO.File.OpenText(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName))
- using (System.IO.StreamReader file = System.IO.File.OpenText(fileName))
- {
- return JsonConvert.DeserializeObject<T>(file.ReadToEnd());
- }
- }
- //Config config = new Config();
- //config= JsonfileTools.ReadjsonT<Config>("SendDataZCCAconfig.json");
- /// <summary>
- /// 写入JSON文件
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="fileName">保存使用的文件路径</param>
- /// <param name="tParameter">实体类</param>
- /// <returns>成功状态</returns>
- public static bool WritejsonT<T>(string fileName, T tParameter)
- {
- //string fp = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName;
- string fp = fileName;
- try
- {
- File.WriteAllText(fp, JsonConvert.SerializeObject(tParameter)); // 覆盖写入
- return true;
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// 修改-Value通过Key(AppSetting)
- /// </summary>
- /// <param name="filePath">文件路径</param>
- /// <param name="key">需要修改的key</param>
- /// <param name="value">更改为的值</param>
- /// <returns></returns>
- public static void ModifyValueByKey(string filePath, string[] key, string value)
- {
- try
- {
- if (!File.Exists(filePath))
- {
- throw new Exception("需要修改的json文件不存在!");
- }
- string jsonStr = File.ReadAllText(filePath, Encoding.UTF8); // 读取文件流
- JObject json = JObject.Parse(jsonStr); // 解析成json
- //json[key] = value; // 修改需要修改的字段
- switch (key.Length)
- {
- case 1:
- json[key[0]] = value;
- break;
- case 2:
- json[key[0]][key[1]] = value;
- break;
- case 3:
- json[key[0]][key[1]][key[2]] = value;
- break;
- default:
- // 目前只用到最多三层的
- break;
- }
- jsonStr = Convert.ToString(json);
- File.WriteAllText(filePath, jsonStr, Encoding.UTF8);
- }
- catch
- {
- throw new Exception($"修改{filePath}文件出错!");
- }
-
- }
- }
- }
|