Using BinaryWriter on an Object

后端 未结 1 1446
时光说笑
时光说笑 2021-01-19 05:02

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, uint3

相关标签:
1条回答
  • 2021-01-19 05:42

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题