FileHelper.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Text;
  2. using Newtonsoft.Json;
  3. namespace Vbdsm.Common
  4. {
  5. public class FileHelper
  6. {
  7. public static T? ReadFileInfo<T>(string fileName) where T : new()
  8. {
  9. var str = ReadFileInfo(fileName);
  10. return Str2Obj<T>(str);
  11. }
  12. public static string ReadFileInfo(string fileName, string path = "Data")
  13. {
  14. string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{path}\\{fileName}.json");
  15. StringBuilder sb = new StringBuilder();
  16. if (File.Exists(filePath)) //文件存在
  17. {
  18. try
  19. {
  20. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  21. StreamReader reader = new StreamReader(fs, Encoding.UTF8);
  22. while (reader.ReadLine() is { } line)
  23. {
  24. sb.Append(line);
  25. }
  26. reader.Close();
  27. fs.Close();
  28. }
  29. catch
  30. {
  31. // ignored
  32. }
  33. }
  34. return sb.ToString();
  35. }
  36. public static void SaveFileInfo(object obj, string fileName)
  37. {
  38. string str = Obj2Str(obj);
  39. SaveFileInfo(str, fileName);
  40. }
  41. public static void SaveFileInfo(string contents, string fileName)
  42. {
  43. string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Data");
  44. if (!Directory.Exists(path))
  45. {
  46. Directory.CreateDirectory(path);
  47. }
  48. string filePath = $"{path}\\{fileName}.json";
  49. File.WriteAllText(filePath, contents);
  50. }
  51. public static T? Str2Obj<T>(string str) where T : new()
  52. {
  53. if (!string.IsNullOrEmpty(str))
  54. {
  55. try
  56. {
  57. return JsonConvert.DeserializeObject<T>(str);
  58. }
  59. catch //(Exception e)
  60. {
  61. return default;
  62. }
  63. }
  64. return default;
  65. }
  66. public static string Obj2Str(object obj)
  67. {
  68. return JsonConvert.SerializeObject(obj, Formatting.Indented);
  69. }
  70. }
  71. }