BinaryFormatter with MemoryStream Question

user195488 picture user195488 · Jun 1, 2010 · Viewed 7.7k times · Source

I am testing BinaryFormatter to see how it will work for me and I have a simple question:

When using it with the string HELLO, and I convert the MemoryStream to an array, it gives me 29 dimensions, with five of them being the actual data towards the end of the dimensions:

            BinaryFormatter bf = new BinaryFormatter();

            MemoryStream ms = new MemoryStream();

            byte[] bytes;
            string originalData = "HELLO";

            bf.Serialize(ms, originalData);
            ms.Seek(0, 0);

            bytes = ms.ToArray();

returns

-       bytes   {Dimensions:[29]}   byte[]
        [0] 0   byte
        [1] 1   byte
        [2] 0   byte
        [3] 0   byte
        [4] 0   byte
        [5] 255 byte
        [6] 255 byte
        [7] 255 byte
        [8] 255 byte
        [9] 1   byte
        [10]    0   byte
        [11]    0   byte
        [12]    0   byte
        [13]    0   byte
        [14]    0   byte
        [15]    0   byte
        [16]    0   byte
        [17]    6   byte
        [18]    1   byte
        [19]    0   byte
        [20]    0   byte
        [21]    0   byte
        [22]    5   byte
        [23]    72  byte
        [24]    69  byte
        [25]    76  byte
        [26]    76  byte
        [27]    79  byte
        [28]    11  byte

Is there a way to only return the data encoded as bytes without all the extraneous information?

Answer

Toby picture Toby · Jun 1, 2010

All of that extraneous information tells the other BinaryFormatter (that will deserialize the object) what type of object is being deserialized (in this case, System.String). Depending on the type, it includes other information needed to reconstruct the object (for instance, if it were a StringBuilder, the Capacity would also be encoded in there.

If all you want to do is stuff a string into a MemoryStream buffer:

        using (MemoryStream ms = new MemoryStream())
        using (TextWriter writer = new StreamWriter(ms))
        {
            writer.Write("HELLO");
            writer.Flush();

            byte[] bytes = ms.ToArray();
        }