5

My application is a small C# database, and I'm using BinaryWriter to save the database to a file which is working fine with the basic types such as bool, uint32 etc.
Although I've got a variable that is of type Object (allowing the user to store any data type), however as my application doesn't (nor needs to) know the real type of this variable, I'm unsure how to write it using BinaryWriter.
Is there a way I could perhaps grab the memory of the variable and save that? Would that be reliable?

Edit:

The answer provided by ba_friend has two functions for de/serialising an Object to a byte array, which can be written along with its length using a BinaryWriter.

R4D4
  • 1,382
  • 2
  • 13
  • 34

1 Answers1

10

You can use serialization for that, especially the BinaryFormatter to get a byte[].
Note: The types you are serializing must be marked as Serializable with the [Serializable] attribute.

public static byte[] SerializeToBytes<T>(T item)
{
    var formatter = new BinaryFormatter();
    using (var stream = new MemoryStream())
    {
        formatter.Serialize(stream, item);
        stream.Seek(0, SeekOrigin.Begin);
        return stream.ToArray();
    }
}

public static object DeserializeFromBytes(byte[] bytes)
{
    var formatter = new BinaryFormatter();
    using (var stream = new MemoryStream(bytes))
    {
        return formatter.Deserialize(stream);
    }
}
ba__friend
  • 5,783
  • 2
  • 27
  • 20
  • Thank you so much, I've worked out how to use that when serialising, although I can't see how to deserialise using this technique - I've updated the question text appropriately. – R4D4 Jul 20 '11 at 10:03
  • Hahaha! :) Oh my, I'm trying to work it out from numerous examples on the net and so far my function is 8 lines long compared to your elegant 3. Thanks for your help. :) – R4D4 Jul 20 '11 at 10:25
  • This works but it's the slowest way to serialize anything in .net by far. – Kelly Elton Jan 03 '16 at 00:57
  • 6
    Microsoft recommends against using BinaryFormatter: https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide – Vitaliy Ulantikov Feb 14 '21 at 20:07