c# - 二进制序列化不起作用, header 无效

标签 c# serialization binaryformatter

我得到了以下内容,而不是复杂的代码,无论如何我在反序列化时遇到了异常。 异常(exception)情况是:二进制流“0”不包含有效的 BinaryHeader。可能的原因是序列化和反序列化之间的无效流或对象版本更改。

但是我不明白我的代码有什么问题

using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;

namespace Server
{
    [Serializable]
    class testclass
    {
        int a;
        int b;
        int c;
        public testclass()
        {
            a = 1;
            b = 2;
            c = 3000;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            testclass test = new testclass();
            IFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(new byte[512],0,512,true,true);
            bf.Serialize(ms,test);
            testclass detest=(testclass)bf.Deserialize(ms);
            Console.ReadLine();
        }
    }
}

最佳答案

您必须先倒回到流的开头,然后才能反序列化或读取您的流示例:ms.Seek(0, SeekOrigin.Begin);

static void Main(string[] args)
    {
        testclass test = new testclass();
        IFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream(new byte[512],0,512,true,true);
        bf.Serialize(ms,test);
        ms.Seek(0,SeekOrigin.Begin); //rewinded the stream to the begining.
        testclass detest=(testclass)bf.Deserialize(ms);
        Console.ReadLine();
    }

关于c# - 二进制序列化不起作用, header 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11501668/

相关文章:

c# - 是否可以序列化 LINQ 对象?

c# - 每路由身份验证导致 RouteExecutionEarlyExitException

c# - 使用 ComboBox.SelectedItem = -1 时 ComboBox 不加载空白值

.net中Newtonsoft.Json.JsonConvert.SerializeObject(Object source,Newtonsoft.Json.JsonSerializerSettings())对应的java代码?

c++ - vector (反)序列化与 Boost.serialization 的向后兼容性

c# - 陷入 C# 序列化困境

c# - 跨程序集移动的反序列化类型

c# - 如何提高反序列化速度?

c# - C# NUnit 的 BDD

c# - 如何使用 LINQ 获取列表中属性的平均值?