insumity
insumity

Reputation: 5459

Serialize an object in C# and get byte stream

I have an object, instance of a Serializable class. I was wondering how can you get this object as a byte stream?

I know I can use BinaryFormatter and then use the Serialize method, but this method takes a serializationStream where it writes the serialized object. I want to be able to write it in a file/stream in a specific position so I would like to do something like:

obj = new Something(); // obj is serializable 
byte[] serialized = obj.serialize(); [*]
file.write(position, serialized)

Is there any way I can do the [*], to take the bytes of the serialization of an object?

Upvotes: 7

Views: 15171

Answers (1)

I4V
I4V

Reputation: 35353

MemoryStream m = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(m, new MyClass() {Name="SO"});
byte[] buf = m.ToArray(); //or File.WriteAllBytes(filename, m.ToArray())


[Serializable]
public class MyClass
{
    public string Name;
}

Upvotes: 13

Related Questions