FlowFileStore.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using TeamAAS.FlowEditor.Models;
  5. namespace TeamAAS.FlowEngine.Execution
  6. {
  7. /// <summary>
  8. /// 流程文件持久化(.aas)。
  9. /// 使用 BinaryFormatter 二进制序列化——CogToolBlock 等 Cognex 对象
  10. /// 实现了 ISerializable,可跟着 FlowGraph 一起完整序列化/反序列化。
  11. /// </summary>
  12. public static class FlowFileStore
  13. {
  14. /// <summary>
  15. /// 保存流程图(二进制)。失败返回 false 并写日志。
  16. /// </summary>
  17. public static bool Save(FlowGraph graph, string path)
  18. {
  19. if (graph == null || string.IsNullOrEmpty(path)) return false;
  20. try
  21. {
  22. var dir = Path.GetDirectoryName(path);
  23. if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
  24. Directory.CreateDirectory(dir);
  25. #pragma warning disable SYSLIB0011
  26. var formatter = new BinaryFormatter();
  27. using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
  28. {
  29. formatter.Serialize(stream, graph);
  30. }
  31. #pragma warning restore SYSLIB0011
  32. return true;
  33. }
  34. catch (Exception ex)
  35. {
  36. AppLogger.Error($"流程保存失败: {path}", ex, nameof(FlowFileStore));
  37. return false;
  38. }
  39. }
  40. /// <summary>
  41. /// 加载流程图(二进制)。
  42. /// </summary>
  43. public static FlowGraph Load(string path)
  44. {
  45. if (string.IsNullOrEmpty(path) || !File.Exists(path)) return null;
  46. try
  47. {
  48. #pragma warning disable SYSLIB0011
  49. var formatter = new BinaryFormatter();
  50. // 绑定器:算子程序集迁移后旧流程仍可加载(未命中映射时与默认行为完全一致)
  51. formatter.Binder = FlowSerializationBinder.Instance;
  52. using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
  53. {
  54. return (FlowGraph)formatter.Deserialize(stream);
  55. }
  56. #pragma warning restore SYSLIB0011
  57. }
  58. catch (Exception ex)
  59. {
  60. AppLogger.Error($"流程加载失败: {path}", ex, nameof(FlowFileStore));
  61. return null;
  62. }
  63. }
  64. }
  65. }