Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 821
insumity Avatar asked Apr 01 '13 19:04

insumity


People also ask

What is serialization in C?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

What does serializing an object do?

To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.


1 Answers

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;
}
like image 146
I4V Avatar answered Sep 27 '22 20:09

I4V