2013-01-24 77 views
0

我希望能夠把通用變量字節數組(將其與EF保存到數據庫)通用讀/寫字節數組

我試着這樣說:

public byte[] SerializedParams { get; set; } // property for EF 

... 

public void Write(params object[] args) 
{ 
    var bf = new BinaryFormatter(); 
    using (var ms = new MemoryStream()) 
    { 
     bf.Serialize(ms, args); 

     SerializedParams = ms.ToArray(); 
    } 
} 

public T Read<T>() 
{ 
    var byteSize = Marshal.SizeOf(typeof(T)); 
    using (var ms = new MemoryStream()) 
    { 
     ms.Write(SerializedParams, 0, SerializedParams.Length); 
     var bf = new BinaryFormatter(); 
     var x = bf.Deserialize(ms); // error here 
     return (T)x; 
    } 
} 

變種x = bf.Deserialize(ms);此行會導致錯誤。 調用後:

qr.Write(5,7,9); 
var i1 = qr.Read<int>(); // error here 
var i2 = qr.Read<int>(); 
var i3 = qr.Read<int>(); 

「流的末尾遇到解析完成之前。」

這是怎麼回事?

+0

[寫入字符串流和回讀不起作用]的可能重複(http://stackoverflow.com/questions/2629612 /寫入字符串到流和讀它,背不 - 不工作) –

回答

0

嘗試將MemoryStream的位置屬性設置爲0:

public T Read<T>() 
{ 
    var byteSize = Marshal.SizeOf(typeof(T)); 
    using (var ms = new MemoryStream()) 
    { 
     ms.Write(SerializedParams, 0, SerializedParams.Length); 
     var bf = new BinaryFormatter(); 
     ms.Position = 0; // this line should do the trick 
     var x = bf.Deserialize(ms); 
     return (T)x; 
    } 
}