c# - How to Serialize object to binary? -
i'm creating phone book in windows forms, , need write contactlist in binaryform save data.
what best way it? shall write several fields seperately, or can write , read full object?
contact has fields :
- guid id
- string name
- string lastname
- string email
- string phonenumber
class (needs serializable
):
[serializable] public class sometype { public int x { set; get; } public int y { set; get; } }
using binary writer:
public static byte[] serialize(sometype obj) { byte[] bytes = null; using (var stream = new memorystream()) { using (var writer = new binarywriter(stream)) { writer.write(obj.x); writer.write(obj.y); } bytes = stream.toarray(); } return bytes; } public static sometype deserialize(byte[] data) { var obj = new sometype(); using (var stream = new memorystream(data)) { using (var reader = new binaryreader(stream)) { obj.x = reader.readint32(); obj.y = reader.readint32(); } } return obj; }
usage:
var obj = new sometype() { x = 10 }; byte[] data = serialize(obj); sometype obj2 = deserialize(data);
or binaryformatter
:
byte[] data = null; using (memorystream ms = new memorystream()) { binaryformatter binaryformatter = new binaryformatter(); binaryformatter.serialize(ms, obj); data = ms.toarray(); } using (memorystream ms = new memorystream(data)) { binaryformatter binaryformatter2 = new binaryformatter(); var objdeserialized = binaryformatter2.deserialize(ms) sometype; }
Comments
Post a Comment