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?
StreamWriter
constructor internally creates an instance ofUTF8Encoding
to do the actual conversion to bytes. If all you need is an array of bytes corresponding to a string, thenMemoryStream
andTextWriter
are not actually the solution - they're just a coincidental way of implicitly creating the class that provides the solution. Just useEncoding.UTF8.GetBytes
directly - or use the correct encoding class for the character encoding you require (UTF-8 is a good default choice). – Ringtail