// 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.Formatters.Binary; using System.Security.Cryptography; using System.Text; namespace E { public class Program { private static DESCryptoServiceProvider key = new DESCryptoServiceProvider() { Key = System.Text.ASCIIEncoding.ASCII.GetBytes("Hejsa du"), IV = new byte[] { 1,2,3,4,5,6,7,8 } }; public static void SerializeObject(string filename, T objectToSerialize) { using (FileStream fs = File.Open(filename, FileMode.Create)) { //using(FileStream cs = fs) using (CryptoStream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write)) { BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(cs, objectToSerialize); } } } public static T DeSerializeObject(string filename) { if (File.Exists(filename)) { using (FileStream fs = File.Open(filename, FileMode.Open)) { //using(FileStream cs = fs) using (CryptoStream cs = new CryptoStream(fs, key.CreateDecryptor(), CryptoStreamMode.Read)) { BinaryFormatter bf = new BinaryFormatter(); return (T)bf.Deserialize(cs); } } } else { return default(T); } } public static void Main(string[] args) { object o = "ABC"; SerializeObject(@"C:\bin.dat", o); object o2 = DeSerializeObject(@"C:\bin.dat"); Console.WriteLine(o2.GetType().Name + " : " + o2.ToString()); } } }