序列化异常:在解析完成之前遇到流结束- c#

本文关键字:遇到 结束 异常 序列化 | 更新日期: 2023-09-27 18:07:10

我正在尝试将字节数组转换为对象。为了消除任何可能的问题,我创建了一个简单的windows窗体,它只调用在我的原始代码中中断的函数,并且我得到了相同的错误。有什么想法吗?

    private void button1_Click(object sender, EventArgs e)
    {
        byte[] myArray = new byte[] {1, 2, 3, 4, 5, 6, 7};
        object myObject = ByteArrayToObject(myArray);
        if(myObject != null)
        {
            button1.Text = "good";
        }
    }
    private object ByteArrayToObject(byte[] arrBytes)
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binForm = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        MemoryStream memStream = new MemoryStream(arrBytes);
        memStream.Position = 0;
        return binForm.Deserialize(memStream);
    }

序列化异常:在解析完成之前遇到流结束- c#

由于您并没有真正说明要对结果对象做什么,因此很难给您一个更具体的答案。然而,一个字节数组已经是一个对象:

private void button1_Click(object sender, EventArgs e)
{
    byte[] myArray = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
    object myObject = myArray as object;
    if (myObject != null)
    {
        button1.Text = "good";
    }
}

BinaryFormatter不只是简单地读写字节。

试试这个例子,首先序列化,然后读取序列化对象的内容:

byte[] myArray = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binForm = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream memStream = new MemoryStream();
// Serialize the array
binForm.Serialize(memStream, myArray);
// Read serialized object
memStream.Position = 0;
byte[] myArrayAgain = new byte[memStream.Length];
memStream.Read(myArrayAgain, 0, myArrayAgain.Length);

结果显示序列化的内容是这样的:

0, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 0, 0, 0, 0, 15, 1, 0, 0, 0, 7, 0, 0, 0, 2, 1, 2, 3, 4, 5, 6, 7, 11

你看,有一个页眉和一个页脚。您的实际对象几乎在末尾。