终端一体化运控平台
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

DataRecord.cs 2.2 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace BPASmartClient.Helper
  10. {
  11. public class DataRecord
  12. {
  13. /// <summary>
  14. /// 读取序列化文件
  15. /// </summary>
  16. /// <param name="FilePath">需要读取序列化文件的文件名,包括后缀名</param>
  17. /// <returns>返回序列化读取到的信息,需要自行转换成对应的类型</returns>
  18. public ReadT Read<ReadT>(string FilePath)
  19. {
  20. if (File.Exists(FilePath))
  21. {
  22. FileStream fs = new FileStream(FilePath, FileMode.Open);
  23. BinaryFormatter bf = new BinaryFormatter();
  24. var res = (ReadT)bf.Deserialize(fs);
  25. fs.Close();
  26. return res;
  27. }
  28. return default;
  29. }
  30. public object Read(string filepath)
  31. {
  32. if (File.Exists(filepath))
  33. {
  34. FileStream fs = new FileStream(filepath, FileMode.Open);
  35. BinaryFormatter bf = new BinaryFormatter();
  36. var res = bf.Deserialize(fs);
  37. fs.Close();
  38. return res;
  39. }
  40. return default;
  41. }
  42. /// <summary>
  43. /// 保存序列化文件
  44. /// </summary>
  45. /// <param name="obj">需要通过序列化保存的对象</param>
  46. /// <param name="FileName">设置保存的文件名,包括后缀名,后缀名可以自定义</param>
  47. public void Save<SaveT>(SaveT obj, string FileName)
  48. {
  49. Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"AccessFile\\ProductionData"));
  50. string path = $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\ProductionData\\{FileName}";
  51. if (obj != null)
  52. {
  53. FileStream fs = new FileStream(path, FileMode.Create);
  54. BinaryFormatter bf = new BinaryFormatter();//创建一个二进制格式化器
  55. bf?.Serialize(fs, obj);
  56. fs.Close();
  57. }
  58. }
  59. }
  60. }