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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -