You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. namespace OT.BLL.Common
  8. {
  9. public class Base64Helper
  10. {
  11. public static string SerializeBase64(object o)
  12. {
  13. // Serialize to a base 64 string
  14. byte[] bytes;
  15. long length = 0;
  16. MemoryStream ws = new MemoryStream();
  17. BinaryFormatter sf = new BinaryFormatter();
  18. sf.Serialize(ws, o);
  19. length = ws.Length;
  20. bytes = ws.GetBuffer();
  21. string encodedData = bytes.Length + ":" + Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
  22. return encodedData;
  23. }
  24. public static object DeserializeBase64(string s)
  25. {
  26. // We need to know the exact length of the string - Base64 can sometimes pad us by a byte or two
  27. int p = s.IndexOf(':');
  28. int length = Convert.ToInt32(s.Substring(0, p));
  29. // Extract data from the base 64 string!
  30. byte[] memorydata = Convert.FromBase64String(s.Substring(p + 1));
  31. MemoryStream rs = new MemoryStream(memorydata, 0, length);
  32. BinaryFormatter sf = new BinaryFormatter();
  33. object o = sf.Deserialize(rs);
  34. return o;
  35. }
  36. }
  37. }