Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing a byte array

If I wanted to fill a structure from a binary file, I would use something like this:

using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
{
    myStruct.ID = br.ReadSingle();
    myStruct.name = br.ReadBytes(20);
}

However, I must read the whole file into a byte array before deserializing, because I want to do some pre-processing. Is there any managed way to fill my structure from the byte array, preferably similar to the one above?

like image 528
Joulukuusi Avatar asked Jul 05 '11 18:07

Joulukuusi


1 Answers

This is a sample to take some data (actually a System.Data.DataSet) and serialize to an array of bytes, while compressing using DeflateStream.

try
{
    var formatter = new BinaryFormatter();
    byte[] content;
    using (var ms = new MemoryStream())
    {
         using (var ds = new DeflateStream(ms, CompressionMode.Compress, true))
         {
             formatter.Serialize(ds, set);
         }
         ms.Position = 0;
         content = ms.GetBuffer();
         contentAsString = BytesToString(content);
     }
}
catch (Exception ex) { /* handle exception omitted */ }

Here is the code in reverse to deserialize:

        var set = new DataSet();
        try
        {
            var content = StringToBytes(s);
            var formatter = new BinaryFormatter();
            using (var ms = new MemoryStream(content))
            {
                using (var ds = new DeflateStream(ms, CompressionMode.Decompress, true))
                {
                    set = (DataSet)formatter.Deserialize(ds);                        
                }
            }
        }
        catch (Exception ex)
        {
            // removed error handling logic!
        }

Hope this helps. As Nate implied, we are using MemoryStream here.

like image 126
Glenn Ferrie Avatar answered Oct 19 '22 22:10

Glenn Ferrie