// 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.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Reflection; namespace Ser { [Serializable] public class GeneralSerializableAdapter : ISerializable { [NonSerialized] private object obj; public GeneralSerializableAdapter(Object o) { obj = o; } private GeneralSerializableAdapter(SerializationInfo info, StreamingContext context) { obj = Assembly.GetExecutingAssembly().CreateInstance(info.GetString("class")); PropertyInfo[] allp = obj.GetType().GetProperties(); foreach(PropertyInfo p in allp) { if(p.PropertyType == typeof(int)) { p.SetValue(obj, info.GetInt32(p.Name), null); } else if(p.PropertyType == typeof(double)) { p.SetValue(obj, info.GetDouble(p.Name), null); } else if(p.PropertyType == typeof(string)) { p.SetValue(obj, info.GetString(p.Name), null); } else { // ignore for now } } } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("class", obj.GetType().FullName); PropertyInfo[] allp = obj.GetType().GetProperties(); foreach(PropertyInfo p in allp) { info.AddValue(p.Name, p.GetValue(obj, null)); } } public object Obj { get { return obj; } } } public class Data { private int iv; private String sv; public int Iv { get { return iv; } set { iv = value; } } public string Sv { get { return sv; } set { sv = value; } } public override string ToString() { return ("[" + iv + ":" + sv + "]"); } } public class Data2 { private String sv; private double xv; public string Sv { get { return sv; } set { sv = value; } } public double Xv { get { return xv; } set { xv = value; } } public override string ToString() { return ("[" + sv + ":" + xv + "]"); } } class Test { public static byte[] Serialize(Object o) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, new GeneralSerializableAdapter(o)); return ms.ToArray(); } public static object Deserialize(byte[] b) { MemoryStream ms = new MemoryStream(b); BinaryFormatter bf = new BinaryFormatter(); ms.Position = 0; return ((GeneralSerializableAdapter)bf.Deserialize(ms)).Obj; } public static void Main(string[] args) { Data o = new Data(); o.Iv = 123; o.Sv = "abc"; Console.WriteLine(o); byte[] b = Serialize(o); Data ox = (Data)Deserialize(b); Console.WriteLine(ox); Data2 o2 = new Data2(); o2.Sv = "xyz"; o2.Xv = 123.456; Console.WriteLine(o2); byte[] b2 = Serialize(o2); Data2 o2x = (Data2)Deserialize(b2); Console.WriteLine(o2x); } } }