Skip to main content

Class serialization, deserialization using Base64 encoding.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConnectionClasses
{
    [Serializable]
    public abstract class Connection
    {
        public int ID { get; set; }

        public String Name { get; set; }

        public string SerializeToBase64String()
        {
            return Connection.SerializeToBase64String(this);
       }

       public static string SerializeToBase64String(Connection connection)
        {
            using (var ms = new MemoryStream())
            {
                new BinaryFormatter().Serialize(ms, connection);
                ms.Seek(0, SeekOrigin.Begin);
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        public static Connection DeserializeFromBase64String(String str)
        {
            using (var ms = new MemoryStream(Convert.FromBase64String(str)))
            {
                ms.Seek(0, SeekOrigin.Begin);
                return (Connection) new BinaryFormatter().Deserialize(ms);
            }
        }
    }
}