using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using TeamAAS.FlowEditor.Models;
namespace TeamAAS.FlowEngine.Execution
{
///
/// 流程文件持久化(.aas)。
/// 使用 BinaryFormatter 二进制序列化——CogToolBlock 等 Cognex 对象
/// 实现了 ISerializable,可跟着 FlowGraph 一起完整序列化/反序列化。
///
public static class FlowFileStore
{
///
/// 保存流程图(二进制)。失败返回 false 并写日志。
///
public static bool Save(FlowGraph graph, string path)
{
if (graph == null || string.IsNullOrEmpty(path)) return false;
try
{
var dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
#pragma warning disable SYSLIB0011
var formatter = new BinaryFormatter();
using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, graph);
}
#pragma warning restore SYSLIB0011
return true;
}
catch (Exception ex)
{
AppLogger.Error($"流程保存失败: {path}", ex, nameof(FlowFileStore));
return false;
}
}
///
/// 加载流程图(二进制)。
///
public static FlowGraph Load(string path)
{
if (string.IsNullOrEmpty(path) || !File.Exists(path)) return null;
try
{
#pragma warning disable SYSLIB0011
var formatter = new BinaryFormatter();
// 绑定器:算子程序集迁移后旧流程仍可加载(未命中映射时与默认行为完全一致)
formatter.Binder = FlowSerializationBinder.Instance;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
{
return (FlowGraph)formatter.Deserialize(stream);
}
#pragma warning restore SYSLIB0011
}
catch (Exception ex)
{
AppLogger.Error($"流程加载失败: {path}", ex, nameof(FlowFileStore));
return null;
}
}
}
}