我知道如何将一个对象序列化为一个字节数组,但是它将整个序列化,有没有办法将它序列化为一块kb?例如,我有一个对象,它将序列化为4mb的大字节数组,而不是同时序列化整个对象,我想一次序列化1kb块,所以它会序列化1kb的价值和传递它,然后继续下一个,直到它完全序列化。我该怎么做呢?
我当前的序列化/反序列化类:
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace TCP_Handler
{
public class SerialMediator
{
/// <summary>
/// Serializes a packet into a byte array
/// </summary>
/// <param name="pkt"></param>
/// <returns></returns>
public static Byte[] Serialize(Packet pkt)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, (Object)pkt);
return ms.ToArray();
}
/// <summary>
/// Deserializes a packet from a byte array
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
public static Packet Deserialize(Byte[] arr)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
ms.Write(arr, 0, arr.Length);
ms.Seek(0, SeekOrigin.Begin);
try
{
return (Packet)bf.Deserialize(ms);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw new Exception("Byte array did not represent a packet");
}
}
}
}