DbHelper.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using Newtonsoft.Json;
  7. namespace SAGA.Models
  8. {
  9. public static class DbHelper
  10. {
  11. static DbHelper()
  12. {
  13. if (!Directory.Exists(Path))
  14. {
  15. Directory.CreateDirectory(Path);
  16. }
  17. }
  18. private static string Path => StaticData.DbDirectory;
  19. /// <summary>
  20. /// 清除所有文件
  21. /// </summary>
  22. public static void ClearAllData()
  23. {
  24. foreach (var file in Directory.GetFiles(Path))
  25. {
  26. File.Delete(file);
  27. }
  28. }
  29. /// <summary>
  30. /// 清除指定的文件
  31. /// </summary>
  32. /// <typeparam name="T"></typeparam>
  33. /// <param name="fileName"></param>
  34. public static void ClearData<T>(string fileName = "")
  35. {
  36. var name = fileName == "" ? GetTableName(typeof(T)) : fileName;
  37. foreach (var file in Directory.GetFiles(Path))
  38. {
  39. if (file.IndexOf(name, StringComparison.Ordinal)>-1)
  40. File.Delete(file);
  41. }
  42. }
  43. /// <summary>
  44. /// 根据文件类型或者文件名保存数据
  45. /// </summary>
  46. /// <typeparam name="T"></typeparam>
  47. /// <param name="t"></param>
  48. /// <param name="fileName"></param>
  49. public static void SaveAsFile<T>(T t, string fileName = "")
  50. {
  51. var name = GetTableNamePath<T>(true, fileName);
  52. var settings = new JsonSerializerSettings();
  53. settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  54. var data = JsonConvert.SerializeObject(t, settings);
  55. //var data = t.ToBinaryString();
  56. File.AppendAllText(name, data);
  57. }
  58. public static List<T> FindAllByFile<T>()
  59. {
  60. var name = GetTableName(typeof(T)) + ".json";
  61. if (File.Exists(name))
  62. {
  63. return JsonConvert.DeserializeObject<List<T>>(File.ReadAllText(name));
  64. }
  65. else
  66. {
  67. return new List<T>();
  68. }
  69. }
  70. /// <summary>
  71. /// 根据文件类型或者文件名获取数据
  72. /// </summary>
  73. /// <typeparam name="T"></typeparam>
  74. /// <param name="tableName"></param>
  75. /// <returns></returns>
  76. public static T FindOneByFile<T>(string tableName = "", bool isCreateTimestamp = true)
  77. {
  78. var name = GetTableNamePath<T>(false, tableName, isCreateTimestamp);
  79. if (File.Exists(name))
  80. {
  81. return JsonConvert.DeserializeObject<T>(File.ReadAllText(name));
  82. // return File.ReadAllText(name).BinaryToObject<T>();
  83. }
  84. var type = typeof(T);
  85. if (type.IsGenericType && type.Name == "List`1")
  86. {
  87. var list = (T)Activator.CreateInstance(type);
  88. return list;
  89. }
  90. return default(T);
  91. }
  92. /// <summary>
  93. /// 根据名称查找文件
  94. /// </summary>
  95. /// <param name="tableName"></param>
  96. /// <returns></returns>
  97. public static string GetFileNamePath(string tableName)
  98. {
  99. var file = Directory.GetFiles(Path).FirstOrDefault(f => f.IndexOf(tableName) > -1);
  100. return file;
  101. }
  102. /// <summary>
  103. /// 根据数据名称生成文件名称
  104. /// </summary>
  105. /// <param name="tableName"></param>
  106. /// <returns></returns>
  107. public static string CreateFileNamePath(string tableName, bool isCreateTimeState = true)
  108. {
  109. var name = System.IO.Path.Combine(Path, tableName + ".json");
  110. if (isCreateTimeState)
  111. name = System.IO.Path.Combine(Path, tableName + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-new.json");
  112. var oldFileName = GetFileNamePath(tableName);
  113. if (File.Exists(oldFileName))
  114. File.Delete(oldFileName);
  115. return name;
  116. }
  117. /// <summary>
  118. /// 根据类型或者数据名称获取数据路径
  119. /// </summary>
  120. /// <typeparam name="T"></typeparam>
  121. /// <param name="isCreate"></param>
  122. /// <param name="tableName"></param>
  123. /// <returns></returns>
  124. public static string GetTableNamePath<T>(bool isCreate, string tableName = "", bool isCreateTimestamp = true)
  125. {
  126. var type = typeof(T);
  127. if (type.IsGenericType && type.Name == "List`1")
  128. {
  129. type = type.GetGenericArguments().FirstOrDefault();
  130. }
  131. var name = tableName == "" ? GetTableName(type) : tableName;
  132. if (!isCreateTimestamp) return System.IO.Path.Combine(Path, name + ".json");
  133. return isCreate ? CreateFileNamePath(name, isCreateTimestamp) : GetFileNamePath(name);
  134. }
  135. /// <summary>
  136. /// 获取拓扑数据的时间戳
  137. /// </summary>
  138. /// <typeparam name="T"></typeparam>
  139. /// <param name="tableName"></param>
  140. /// <returns></returns>
  141. public static string GetTimestamp<T>(string tableName = "")
  142. {
  143. Regex reg = new Regex(@"^\w+-(\d+)(-new)?.json$");
  144. var filePath = GetTableNamePath<T>(false, tableName);
  145. var fileName = System.IO.Path.GetFileName(filePath);
  146. if (!string.IsNullOrEmpty(fileName))
  147. {
  148. var mathch = reg.Match(fileName);
  149. if (mathch.Success)
  150. {
  151. var timestamp = mathch.Groups[1].Value;
  152. return FormatDateTime(timestamp);
  153. }
  154. }
  155. return null;
  156. }
  157. public static string FormatDateTime(string timeStr)
  158. {
  159. Regex dateReg = new Regex(@"^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})");
  160. //转换成可以直接转换的时间格式
  161. var timestamp = dateReg.Replace(timeStr, "$1-$2-$3 $4:$5:$6");
  162. // DateTime no1 = DateTime.ParseExact(timeStr, "yyyyMMddHHmmss", null);
  163. return timestamp;
  164. }
  165. private static string GetTableName(Type type)
  166. {
  167. //检测类型是否为泛型
  168. if (type.GetType().IsGenericType)
  169. {//取出泛型类型
  170. var types = type.GetGenericArguments();
  171. type
  172. = types.FirstOrDefault();
  173. }
  174. var name = type.GetAttribute<TableNameAttribute>()?.Name;
  175. if (string.IsNullOrEmpty(name))//找不到标记名称取类型名称
  176. {
  177. name = type.Name;
  178. }
  179. return name;
  180. }
  181. }
  182. public static class RefletcExtend
  183. {
  184. public static T GetAttribute<T>(this Type type) where T : Attribute
  185. {
  186. return (T)type.GetCustomAttributes(typeof(T), false).FirstOrDefault();
  187. }
  188. }
  189. public class TableNameAttribute : Attribute
  190. {
  191. public string Name { get; set; }
  192. public TableNameAttribute(string name)
  193. {
  194. this.Name = name;
  195. }
  196. }
  197. }