JsonFileHelper.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.IO;
  5. using System.Text;
  6. namespace MainForm.Common
  7. {
  8. public class JsonFileHelper
  9. {
  10. /// <summary>
  11. /// 读取JSON文件
  12. /// </summary>
  13. /// <typeparam name="T">返回的类型</typeparam>
  14. /// <param name="fileName">打开的文件路径</param>
  15. /// <returns>实体类</returns>
  16. public static T ReadjsonT<T>(string fileName)
  17. {
  18. //using (System.IO.StreamReader file = System.IO.File.OpenText(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName))
  19. using (System.IO.StreamReader file = System.IO.File.OpenText(fileName))
  20. {
  21. return JsonConvert.DeserializeObject<T>(file.ReadToEnd());
  22. }
  23. }
  24. //Config config = new Config();
  25. //config= JsonfileTools.ReadjsonT<Config>("SendDataZCCAconfig.json");
  26. /// <summary>
  27. /// 写入JSON文件
  28. /// </summary>
  29. /// <typeparam name="T"></typeparam>
  30. /// <param name="fileName">保存使用的文件路径</param>
  31. /// <param name="tParameter">实体类</param>
  32. /// <returns>成功状态</returns>
  33. public static bool WritejsonT<T>(string fileName, T tParameter)
  34. {
  35. //string fp = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName;
  36. string fp = fileName;
  37. try
  38. {
  39. File.WriteAllText(fp, JsonConvert.SerializeObject(tParameter)); // 覆盖写入
  40. return true;
  41. }
  42. catch
  43. {
  44. return false;
  45. }
  46. }
  47. /// <summary>
  48. /// 修改-Value通过Key(AppSetting)
  49. /// </summary>
  50. /// <param name="filePath">文件路径</param>
  51. /// <param name="key">需要修改的key</param>
  52. /// <param name="value">更改为的值</param>
  53. /// <returns></returns>
  54. public static void ModifyValueByKey(string filePath, string[] key, string value)
  55. {
  56. try
  57. {
  58. if (!File.Exists(filePath))
  59. {
  60. throw new Exception("需要修改的json文件不存在!");
  61. }
  62. string jsonStr = File.ReadAllText(filePath, Encoding.UTF8); // 读取文件流
  63. JObject json = JObject.Parse(jsonStr); // 解析成json
  64. //json[key] = value; // 修改需要修改的字段
  65. switch (key.Length)
  66. {
  67. case 1:
  68. json[key[0]] = value;
  69. break;
  70. case 2:
  71. json[key[0]][key[1]] = value;
  72. break;
  73. case 3:
  74. json[key[0]][key[1]][key[2]] = value;
  75. break;
  76. default:
  77. // 目前只用到最多三层的
  78. break;
  79. }
  80. jsonStr = Convert.ToString(json);
  81. File.WriteAllText(filePath, jsonStr, Encoding.UTF8);
  82. }
  83. catch
  84. {
  85. throw new Exception($"修改{filePath}文件出错!");
  86. }
  87. }
  88. }
  89. }