Class serialization/deserialization using Base64 encoding


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4.  
  5. namespace ConnectionClasses
  6. {
  7. [Serializable]
  8. public abstract class Connection
  9. {
  10. public int ID { get; set; }
  11.  
  12. public String Name { get; set; }
  13.  
  14. public string SerializeToBase64String()
  15. {
  16. return Connection.SerializeToBase64String(this);
  17. }
  18.  
  19. public static string SerializeToBase64String(Connection connection)
  20. {
  21. using (var ms = new MemoryStream())
  22. {
  23. new BinaryFormatter().Serialize(ms, connection);
  24. ms.Seek(0, SeekOrigin.Begin);
  25. return Convert.ToBase64String(ms.ToArray());
  26. }
  27. }
  28.  
  29. public static Connection DeserializeFromBase64String(String str)
  30. {
  31. using (var ms = new MemoryStream(Convert.FromBase64String(str)))
  32. {
  33. ms.Seek(0, SeekOrigin.Begin);
  34. return (Connection) new BinaryFormatter().Deserialize(ms);
  35. }
  36. }
  37. }
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.