0

I am trying to convert class to byte but not worked.

I receive a byte[] (b) with zero length . why ?

void start() { Item item = new Item(); item.files.Add(@"test"); byte[] b = ObjectToByteArray(item); // b will have zero length } [Serializable] public class Item : ISerializable { public Item() { files = new List<string>(); Exclude = false; CleanEmptyFolder = false; } public List<string> files; public string MusicProfileName; public bool Exclude; #region ISerializable Members public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("files", files); info.AddValue("MusicProfileName", MusicProfileName); info.AddValue("Exclude", Exclude); } #endregion } public byte[] ObjectToByteArray(object _Object) { using (var stream = new MemoryStream()) { // serialize object var formatter = new BinaryFormatter(); formatter.Serialize(stream, _Object); // get a byte array var bytes = new byte[stream.Length]; using (BinaryReader br = new BinaryReader(stream)) { bytes = br.ReadBytes(Convert.ToInt32(stream.Length)); } return bytes; } } 

2 Answers 2

4

You didn't reset the MemoryStream before you started to read from it. The position is at the end of the stream, so you get an empty array.

Use the ToArray method instead, it gets the entire content regardless of the current position:

public byte[] ObjectToByteArray(object _Object) { using (var stream = new MemoryStream()) { // serialize object var formatter = new BinaryFormatter(); formatter.Serialize(stream, _Object); // get a byte array return stream.ToArray(); } } 
Sign up to request clarification or add additional context in comments.

Comments

3

Try using MemoryStream.ToArray instead of trying to read from the MemoryStream with a BinaryReader:

return stream.ToArray(); 

The problem is that you aren't resetting the stream, so it's trying to read from the end instead of the beginning. You could also seek back to the beginning of the stream:

stream.Seek(0, SeekOrigin.Begin); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.