2015-05-07 78 views
-3

我有一个byte[],我需要反序列化它。使用BinaryReader反序列化失败

我写了这个代码

using(MemodyStream stream = new MemoryStream(byteArray) 
    { 
     using(BinaryReader reader = new BinaryReader(stream)) 
     { 
      Person p = new Person(); 
      p.id = reader.ReadString(); 
      p.age = reader.ReadInt32(); 
     } 
    } 

但我不明白为什么我看到BinaryReader返回0每次=>和byteArray不包含0

哪里是我的错?

如何以另一种方式做到这一点?

添加..

在我写这篇文章的数据以相同的顺序

using(BinaryWriter w = new BinaryWriter(stream)) 
    { 
     w.Write(person.id); 
     w.Write(person.age); 
    } 
+0

你是怎么写'byteArray'的? “ReadString”和“ReadInt32”要求数据以某种方式进行格式化......特别是“ReadString”在格式化方面非常特别,并且BinaryWriter之外的其他内容不可能格式化这样的数据。 – xanatos

+0

添加了作家 – Yanshof

+0

作家是从其他应用程序完成的(使用C++写的) – Yanshof

回答

1

我认为每一个事情是确定的,问题就必须在serilize:

我用这个代码和好的:

 int myInt = 100; 
     byte[] byteArray = BitConverter.GetBytes(myInt); 

     using (MemoryStream stream = new MemoryStream(byteArray)) { 
      using (BinaryReader reader = new BinaryReader(stream)) { 
       var i = reader.ReadInt32(); 
      } 
     } 
+0

好吧,我还测试了一些我写的serilize - 我也得到了很好的结果。 – Yanshof

+0

@Yanshof你能解释你如何序列化? –

+0

是的,通过使用BinaryWriter.Write – Yanshof