How to convert a 2D binary object in to a Dictonary<string, object> in C# using Binary Formatter

72 Views Asked by At

I want to convert an objeect of byte[][] type to Dictonary.

It always give an error "End of Stream encountered before parsing was completed."

Please help me .

 public static object ByteToObjectArray(byte[][] ms)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream mStream = new MemoryStream();
        mStream.Write(ms, 0, (int)ms.Length);
        mStream.Position = 0;
        return formatter.Deserialize(mStream) as object;

    }
1

There are 1 best solutions below

0
xanatos On

The HGETALL should return the data as

key1
data1
key2
data2
...

So interleaved... Now... Supposing the key is in UTF8:

public static Dictionary<string, object> ByteToObjectArray(byte[][] bytes)
{
    var dict = new Dictionary<string, object>();
    var formatter = new BinaryFormatter();

    for (int i = 0; i < bytes.Length; i += 2)
    {
        string key = Encoding.UTF8.GetString(bytes[i]);
        // Alternatively
        //string key = Encoding.Unicode.GetString(bytes[i]);

        using (var stream = new MemoryStream(bytes[i + 1]))
        {
            object obj = formatter.Deserialize(stream);

            dict.Add(key, obj);
        }
    }

    return dict;
}