首页 > 解决方案 > 如何在从字节数组反序列化时确定字符串的长度?

问题描述

我使用MessagePackSerializer并尝试反序列化字节数组。但是数组可能非常大(10-20 MB)。

我正在将数据读入 1000 字节的中间缓冲区。我从他们那里读取数据。

但是有一个问题:当我尝试读取一行太长时,可能会出现错误

System.ArgumentOutOfRangeException: Index and count must refer 
to a location within the buffer.

我不知何故需要找出我要读取的行超出了数组的范围,我需要将缓冲区扩展到行的大小。

我该怎么做?

我使用这段代码:

var stringValue = MessagePackBinary.ReadString(bytes, off, out readSize);

简单的例子:

public class Example
{


    public void Serialize(Stream inputStream,string value)
    {
        MessagePackBinary.WriteString(inputStream, value);
    }

    public string Deserealize(Stream stream)
    {
        var off = 0;
        byte[] bytes = new byte[1000];
        int readSize = 0;

        stream.Read(bytes, off, bytes.Length);
        var stringValue = MessagePackBinary.ReadString(bytes, off, out readSize); //string can be very long
        return stringValue;
    }
}

标签: c#serializationdeserializationmsgpack

解决方案


20MB 现在真的不是那么多,即使在手机上也是如此。只需将整个数组读入内存并解码即可。


推荐阅读