二进制序列化不起作用,无效标头

时间:2012-07-16 09:35:30

标签: c# serialization binaryformatter

我得到以下内容,而不是comlex代码,无论如何我在反序列化时遇到异常。 例外情况是:二进制流“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();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

当您执行

时,您的信息流就在数据的末尾
bf.Serialize(ms,test);

在尝试

之前将其倒回
testclass detest=(testclass)bf.Deserialize(ms);

在流上使用Position=0来执行此操作。

答案 1 :(得分:2)

您必须首先回滚到流的开头,之后您可以反序列化或读取您的流示例: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();
    }