我有以下代码片段,它在TcpClient
网络流上接收消息,该消息可能包含obj
类型形式的某些内容,并尝试将其序列化为字节数组:
let readStreamToFile (client:TcpClient) outputPath =
let formatter = new BinaryFormatter()
try
let message = (formatter.Deserialize (client.GetStream ())) :?> Message
match message.Type with
| FileTransfer ->
match message.Content with
| Some content ->
let bytesContent =
use mStream = new MemoryStream()
formatter.Serialize (mStream, content)
mStream.ToArray ()
File.WriteAllBytes (outputPath, bytesContent)
| None ->
failwith "There was no content in the FileSync message!!!"
| _ ->
()
with
| :? InvalidCastException as ex ->
failwith "Message format unknown!!!"
不幸的是,当我调试此代码时,我可以看到收到的内容很好,长度为46,但mStream.ToArray ()
之后对formatter.Serialize (mStream, content)
的调用长度为74。是的,它增加了28项之前实际的长度为46的数组。这28项也不是空的,有些包含值。
这是正常的吗?如何才能bytesContent
始终与obj
content
相同?
答案 0 :(得分:3)
BinaryFormatter对序列化对象的类型信息和值进行编码。在反序列化时重建对象需要类型信息。额外的字节是类型信息。