我得到了以下内容,而不是复杂的代码,无论如何我在反序列化时遇到了异常。 异常(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/