This code snippet article is giving code examples to Convert object to byte array and Convert byte array to object in C#
You can convert object into byte array and byte array into object easily by using serialization in C#.
Note: for custom classes add [Serializable] attribute to enable serialization
Convert object to byte array
private byte[] ObjectToByteArray(Object obj) { if (obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); return ms.ToArray(); }
Convert byte array to object
private Object ByteArrayToObject(byte[] arrBytes) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); Object obj = (Object) binForm.Deserialize(memStream); return obj; }
Related Articles:
– Get current time on a remote system using C#
– Convert DateTime to Ticks and Ticks to DateTime in C#
– Add or Remove programs using C# in Control Panel
– Show balloon tooltip c#
– How to read data from csv file in c#
– Bulk Insert into SQL Server using SqlBulkCopy in C#
– Import CSV File Into SQL Server Using SQL Bulk Copy
Advertisement
Hello Morgan,
I get an exception: End of Stream encountered before parsing was completer.
This is my code:
public Object GmReadDataToPointerAdress (uint PointerValue, short NrOffBytesRead)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
// Create array size off number off bytes to send
byte[] rx = new byte[NrOffBytesRead];
// Receive bytes from plc
Lasal32.GetDataH(lvocb, rx, PointerValue, NrOffBytesRead);
// Copy received byte to strema
memStream.Write(rx, 0, rx.Length);
// Set seek to begin
//memStream.Seek(0, SeekOrigin.Begin);
memStream.Position = 0;
// Deserialize to object
Object obj = (Object)binForm.Deserialize(memStream);
// Return object
return obj;
}
Can you help me please ?
I get the same error. Did you ever figure this out?
Thank you so much!
Thank you
Hi Morgan,
I get an exception"Unable to find assembly 'MyService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'." during deserialization.
Please help .
thank You
excellent thank you so much
Thank you