【问题标题】:Binary serialization not working, not valid header二进制序列化不起作用,无效标头
【发布时间】:2012-07-16 09:35:30
【问题描述】:

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

【问题讨论】:

    标签: c# serialization binaryformatter


    【解决方案1】:

    您必须先倒回到流的开头,然后才能反序列化或读取流示例: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();
        }
    

    【讨论】:

    • 好的,我不仅需要倒带,而且我的消息必须从 0 开始,但我仍然有一些问题,我会用更多代码更新我的问题
    • 好的,但是如果它是一个新问题,请发布一个新问题,然后单击已解决问题的答案。
    • 好的,最后一个问题是关于不知道我自己的协议,所以谢谢你们指出问题
    【解决方案2】:

    当您这样做时,您的信息流位于数据的末尾

    bf.Serialize(ms,test);
    

    在尝试之前倒带开始

    testclass detest=(testclass)bf.Deserialize(ms);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多