// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace E { [Serializable] public struct ST_Log { public int ProjectId; public int ChannelNumber; public int Value; public DateTime CreationTime; public bool Delete; public bool Invalid; } internal static class SerUtil { public static byte[] Object2ByteArray(T o) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, o); return ms.ToArray(); } public static string Object2String(T o) { return Convert.ToBase64String(Object2ByteArray(o)); } public static T ByteArray2Object(byte[] b) { MemoryStream ms = new MemoryStream(b); BinaryFormatter bf = new BinaryFormatter(); ms.Position = 0; return (T)bf.Deserialize(ms); } public static T String2Object(string s) { return ByteArray2Object(Convert.FromBase64String(s)); } } public class Program { public static byte[] PlainBinarySerialization(List data) { return SerUtil>.Object2ByteArray(data); } public static byte[] CompressingBinarySerialization(List data) { MemoryStream ms = new MemoryStream(); GZipStream cmp = new GZipStream(ms, CompressionMode.Compress); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(cmp, data); cmp.Close(); return ms.ToArray(); } public static void Test(List data, Func, byte[]> f, string lbl) { byte[] b = f(data); Console.WriteLine("{0} : {1}", lbl, b.Length); } public static void Main(string[] args) { List data = new List { new ST_Log { ProjectId=1, ChannelNumber=1, Value=123, CreationTime=DateTime.Now, Delete=false, Invalid=false }, new ST_Log { ProjectId=2, ChannelNumber=1, Value=456, CreationTime=DateTime.Now, Delete=false, Invalid=false }, new ST_Log { ProjectId=3, ChannelNumber=1, Value=789, CreationTime=DateTime.Now, Delete=false, Invalid=false }, new ST_Log { ProjectId=4, ChannelNumber=1, Value=123, CreationTime=DateTime.Now, Delete=false, Invalid=false }, new ST_Log { ProjectId=5, ChannelNumber=1, Value=456, CreationTime=DateTime.Now, Delete=false, Invalid=false } }; Test(data, PlainBinarySerialization, "Plain binary serializer"); Test(data, CompressingBinarySerialization, "Compressing binary serializer"); } } }