Serialization.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 Ant.Frame
  8. {
  9. public static class Serialization
  10. {
  11. #region 对实体类进行序列化和反序列化
  12. /// <summary>
  13. /// 将对象序列化
  14. /// </summary>
  15. /// <param name="obj"></param>
  16. /// <returns></returns>
  17. private static MemoryStream Serialize(object obj)
  18. {
  19. try
  20. {
  21. BinaryFormatter formatter = new BinaryFormatter();
  22. MemoryStream ms = new MemoryStream();
  23. formatter.Serialize(ms, obj);
  24. return ms;
  25. }
  26. catch
  27. {
  28. return null;
  29. }
  30. }
  31. /// <summary>
  32. ///
  33. /// </summary>
  34. /// <param name="obj"></param>
  35. /// <param name="stream"></param>
  36. /// <returns></returns>
  37. private static Stream Serialize(object obj, Stream stream)
  38. {
  39. try
  40. {
  41. BinaryFormatter formatter = new BinaryFormatter();
  42. formatter.Serialize(stream, obj);
  43. return stream;
  44. }
  45. catch
  46. {
  47. return null;
  48. }
  49. }
  50. /// <summary>
  51. /// 序列化
  52. /// </summary>
  53. /// <param name="stream"></param>
  54. /// <returns></returns>
  55. private static object Deserialize(Stream stream)
  56. {
  57. try
  58. {
  59. BinaryFormatter formatter = new BinaryFormatter();
  60. return formatter.Deserialize(stream);
  61. }
  62. catch
  63. {
  64. return null;
  65. }
  66. }
  67. /// <summary>
  68. /// 将实体或datatable转换为string
  69. /// </summary>
  70. /// <param name="obj"></param>
  71. /// <returns></returns>
  72. public static string SerializeToString(object obj)
  73. {
  74. try
  75. {
  76. MemoryStream msObj = Serialize(obj);
  77. return Convert.ToBase64String(msObj.ToArray());
  78. }
  79. catch
  80. {
  81. return null;
  82. }
  83. }
  84. /// <summary>
  85. /// 将string转换为对象
  86. /// </summary>
  87. /// <param name="str"></param>
  88. /// <returns></returns>
  89. public static object DeserializeFromString(string str)
  90. {
  91. try
  92. {
  93. byte[] byteArrayObj = Convert.FromBase64String(str);
  94. Stream myObj = new MemoryStream(byteArrayObj);
  95. return Deserialize(myObj);
  96. }
  97. catch
  98. {
  99. return null;
  100. }
  101. }
  102. #endregion
  103. }
  104. }