Search code examples
c#databasedeserializationstoragebinary-serialization

Serializing a complex object and Deserializing as string for storage - Will it work?


I am using System.Runtime.Serialization.Formatters.Binary.BinaryFormatter to Serialize a complex Project object and store it as a .dat file on the local machine. Then I can deserialize this stream and cast to Project to get an exact copy of the original project. The (simplified) code is as follows:

Project project = new Project();
FileStream stream = new FileStream("file.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, project);
stream.Close();

...

stream = new FileStream("file.dat", FileMode.Open);
Project revisitedProject = (Project)formatter.Deserialize(stream);
stream.Close();

and this works for me with no loss of data, as it should. However, this only allows me to store the project on the local machine, so if the device is lost or damaged then so are all of the user's projects. The Project class is too complex to store in a table, so I'm hoping that somebody with more knowledge of Serialization can help me out a bit because I'm very beginner with the concept.

I would like to serialize the project just like I already do.

Then, I want to deserialize the project and cast to a string, this string will be stored in a table.

If the project ever needs to be recovered, that string will be serialized once again and stored in the local machine as a .dat file.

Then, if I deserialize that .dat file and cast it to Project, will I have an exact copy of my original project or would casting and storing it as a string have caused me to lose data?


Solution

  • When you have your .dat file, you already have a serialized version of the complex object, no need to turn this into string. All modern databases support storing data as a blob: that is, data without structure that would be understood by the database engine. You can store the content of your .dat file(s) in a database, in a blob field. Different databases call this data type in a different way, e.g. MSSQL calls it varbinary.

    As an addition, if you insist converting to string, consider converting the binary using base64. It will make it safe both encoding and decoding without codepage and language encoding concerns.