You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 7.0反序列化.NET 4.8的CogToolBlock对象遇阻求助

.NET Core 7.0 Blazor中反序列化Cognex VisionPro对象的问题

补充说明

  • 受Cognex VisionPro商业许可证限制,无法提供最小可复现示例
  • 无法修改CogToolBlock或CogSerializer类的代码

背景

我需要在.NET Core 7.0服务器端Blazor应用中使用基于.NET 4.8开发的商用图像分析库Cognex VisionPro(无需使用其UI组件),需完成以下操作:

  1. 在不可修改的.NET 4.8商用程序中序列化文件
  2. 在我的.NET Core 7.0应用中反序列化该文件

问题

执行反序列化代码时出现错误:

// 此代码位于.NET Core 7.0中,无法修改CogToolBlock或CogSerializer类
CogToolBlock toolblock = CogSerializer.LoadobjectFromFile(filePath);

报错信息:

Could not load file or assembly 'System.Runtime.Serialization.Formatters.Soap, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

根本原因:.NET Core中BinaryFormatter已被弃用。

已尝试方案

  1. 参考GitHub issue尝试使用CoreFX,但因对象类型复杂,未解决问题
  2. 按MSDN文档配置<EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>启用BinaryFormatter,在.NET 4.8程序中执行序列化:
// .NET 4.8应用中的代码
var toolblock = CogSerializer.LoadObjectFromFile(@"C:\tmp\sequence.vpp"); 
using (var fs= new FileStream(@"C:\tmp\sequence.vpp.dat", FileMode.Create))
{
    var formatter = new BinaryFormatter();
    formatter.Serialize(fs, Serialize(toolblock));
}

// 将实例转换为字节数组的方法
private static byte[] Serialize(CogToolBlock obj)
{
    using (var memoryStream = new MemoryStream())
    {
        var binaryFormatter = new BinaryFormatter(); // 使用BinaryFormatter
        binaryFormatter.Serialize(memoryStream, obj);
        return memoryStream.ToArray();
    }
}

生成的sequence.vpp.dat与原文件大小一致,但在Blazor应用中执行反序列化代码时仍报错:

byte[] fileBytes = File.ReadAllBytes(@"C:\tmp\sequence.vpp.dat");
CogToolBlock = Deserialize(fileBytes); 

// 反序列化方法
private static CogToolBlock Deserialize(byte[] data)
{
    using (var memoryStream = new MemoryStream(data))
    {
        var binaryFormatter = new BinaryFormatter();
        return binaryFormatter.Deserialize(memoryStream) as CogToolBlock; // 错误发生在此处
    }
}
  1. 尝试使用Google Protobuf,但提示No serializer defined for type: Cognex.VisionPro.ToolBlock.CogToolBlock,无法序列化复杂对象

请求

恳请提供解决思路或相关指引。


内容的提问来源于stack exchange,提问作者Christian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:45:55