How can I convert a Class to byte array in C#. This is a managed one so the following code is failing
int objsize = System.Runtime.InteropServices.Marshal.SizeOf(objTimeSeries3D);
byte[] arr = new byte[objsize];
IntPtr buff = System.Runtime.InteropServices.Marshal.AllocHGlobal(objsize);
System.Runtime.InteropServices.Marshal.StructureToPtr(objTimeSeries3D, buff, true);
System.Runtime.InteropServices.Marshal.Copy(buff, arr, 0, objsize);
System.Runtime.InteropServices.Marshal.FreeHGlobal(buff);
Thanks
Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.
You can use BinaryFormatter
. Note that your class must be [Serializable]
for this to work.
private byte[] ToByteArray(object source)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, source);
return stream.ToArray();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With