Reputation: 5459
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
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