Search code examples
c#serializationvarbinary

Deserialize varbinary in file


I'm working on this: I have some file and I insert their properties in a database, including corresponding varbinary. I do it this way: I convert it in mimedata, then I serialize them in a binaryformatter obtainining a byte array. So I insert the result in a db with sql.

So, the process that you could use to deserialize is to reverse, but, my question is, there is a faster way to do it?


Solution

  • Here's a small example:

    Car car = new Car("BMW");
    
    BinaryFormatter bFormatter = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bFormatter.Serialize(ms, car);
    System.Data.Linq.Binary carBinary 
        = new System.Data.Linq.Binary(ms.ToArray());
    
    TestDB db = new TestDB(ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString);
    db.InsertObjectSerialize(carBinary);
    
    ISingleResult<GetObjectSerializeResult> result = db.GetObjectSerialize(1);
    System.Data.Linq.Binary carBinaryFromDB
        = result.Single().Object;
    ms = new MemoryStream(carBinaryFromDB.ToArray());
    
    Car carFromDB = (Car)bFormatter.Deserialize(ms);
    

    Taken from here.