0

I have an ObservableCollection<Employee> how do I convert it into byte array[]?

The class Employee consists of, - EmployeeId - DateOfJoining - Age - Salary

The service I need to pass the collection to is expecting the data to be in byte[].
What would be an efficient way to convert observableCollection to byte[]?
Or do I just need to loop through the collection to create a byte array?

1
  • 1
    The service I need to pass the collection to is expecting the data to be in byte[] In what format/protocol? BinaryFormatter is only one of the many alternatives. for ex, int i = 1; binaryWriter.Write(i); or Encoding.ASCII.GetBytes(i.ToString()); Commented May 12, 2013 at 22:54

2 Answers 2

1

you can use a Binary Formatter to serialize your collection.

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx

var employees = new ObservableCollection<Employee>();


using (var stream = new MemoryStream())
{    
    var formatter = new BinaryFormatter();
    formatter.Serialize(stream, employees);
    var byteArray = new byte[stream.Length];
    stream.Seek(0, SeekOrigin.Begin);
    stream.Read(byteArray, 0, (int)stream.Length);
    // do whatever you want with the bytes now....

}
Sign up to request clarification or add additional context in comments.

1 Comment

You could cut out the alloc of the byte array because memorystream already does that for you. ToArray (copy) or GetBuffer (direct)
0

You have choices like Protobuf, Protobuf-Net, your own custom BinaryWriter "ToBytes, FromBytes". It really depends on what your receiving end desires, and whether they are using a generic documented format or a custom one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.