2012-07-16 30 views
1

我得到了下面,而不是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

你必須後退到流的第一後,你可以反序列化或閱讀數據流實例的開始: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

確定不僅我一定要倒帶流,但我的消息在0開始,但我仍然有一些問題,我會更新我的問題有一些更多的代碼 – 2012-07-16 10:58:35

+0

確定,但如果它的一個新的問題,請發佈一個新的,點擊就解決你的問題的答案回答。 – Freeman 2012-07-16 11:01:22

+0

確定最後一個問題是關於不知道我自己的協議,所以感謝你們倆指出該問題, – 2012-07-16 11:04:05

2

你流在你的數據的結尾,當你做

bf.Serialize(ms,test); 

倒帶試圖

之前啓動
testclass detest=(testclass)bf.Deserialize(ms); 

在流使用Position=0做到這一點。