ObjectSerializer.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6. using System.Xml.Serialization;
  7. using System.Runtime.Serialization;
  8. using System.Runtime.Serialization.Formatters;
  9. using System.Runtime.Serialization.Formatters.Binary;
  10. using System.IO;
  11. using System.Reflection;
  12. using Aitex.Core.RT.Log;
  13. namespace Aitex.Core.Util
  14. {
  15. /// <summary>
  16. /// class 'ObjectSerializer' provides a set of utilities which serialize objects to xml or binary file,
  17. /// or deserialize xml or binary file back to objects.
  18. /// </summary>
  19. public sealed class ObjectSerializer
  20. {
  21. private ObjectSerializer() { }
  22. /// <summary>
  23. /// Serialize the supplied object To memory stream in xml format.
  24. /// </summary>
  25. /// <param name="valueToSerializeToMemoryStream"></param>
  26. /// <returns></returns>
  27. public static MemoryStream SerializeObjectToMemoryStream(object valueToSerializeToMemoryStream)
  28. {
  29. var retVal = new MemoryStream();
  30. var typeToSerialize = valueToSerializeToMemoryStream.GetType();
  31. var serializer = new XmlSerializer(typeToSerialize);
  32. serializer.Serialize(retVal, valueToSerializeToMemoryStream);
  33. retVal.Seek(0, SeekOrigin.Begin);
  34. return retVal;
  35. }
  36. /// <summary>
  37. ///
  38. /// </summary>
  39. /// <param name="obj"></param>
  40. /// <returns></returns>
  41. public static XmlDocument SerializeObjectToXmlDom(object obj)
  42. {
  43. Stream stream = SerializeObjectToMemoryStream(obj);
  44. XmlDocument xmldom = new XmlDocument();
  45. xmldom.Load(stream);
  46. return xmldom;
  47. }
  48. private static Type[] RemoveDuplicateType(Type typeOfObject, IEnumerable<Type> types)
  49. {
  50. var typeList = new List<Type>();
  51. foreach (var type in types)
  52. {
  53. if (!type.FullName.Equals(typeOfObject.FullName))
  54. {
  55. typeList.Add(type);
  56. }
  57. }
  58. return typeList.ToArray();
  59. }
  60. /// <summary>
  61. /// Serialize derived types to xml stream, SeekOrigin set to Begin.
  62. /// </summary>
  63. /// <param name="valueToSerializeToMemoryStream"></param>
  64. /// <param name="types"></param>
  65. /// <returns></returns>
  66. public static MemoryStream SerializeObjectToMemoryStream(object valueToSerializeToMemoryStream, Type[] types)
  67. {
  68. var retVal = new MemoryStream();
  69. var typeToSerialize = valueToSerializeToMemoryStream.GetType();
  70. types = RemoveDuplicateType(typeToSerialize, types);
  71. var serializer = new XmlSerializer(typeToSerialize, types);
  72. serializer.Serialize(retVal, valueToSerializeToMemoryStream);
  73. retVal.Seek(0, SeekOrigin.Begin);
  74. return retVal;
  75. }
  76. /// <summary>
  77. /// Serialize the supplied object To binary stream, SeekOrigin set to Begin.
  78. /// </summary>
  79. /// <param name="valueToSerializeToMemoryStream"></param>
  80. /// <returns></returns>
  81. public static MemoryStream SerializeObjectToBinaryStream(object valueToSerializeToMemoryStream)
  82. {
  83. // Converts object [objectToSerialize] of type [typeOfObjectBeingSerialized] to a memory stream
  84. var retVal = new MemoryStream();
  85. IFormatter formatter = new BinaryFormatter();
  86. formatter.Serialize(retVal, valueToSerializeToMemoryStream);
  87. retVal.Seek(0, SeekOrigin.Begin);
  88. return retVal;
  89. }
  90. /// <summary>
  91. /// Serializes an object into a file using binary formatter.
  92. /// </summary>
  93. /// <param name="fullFileName"></param>
  94. /// <param name="valueToSerialize"></param>
  95. /// <returns></returns>
  96. public static bool SerializeObjectToBinaryFile(string fullFileName, object valueToSerialize)
  97. {
  98. try
  99. {
  100. using (FileStream stream = new FileStream(fullFileName, FileMode.OpenOrCreate))
  101. {
  102. IFormatter formatter = new BinaryFormatter();
  103. formatter.Serialize(stream, valueToSerialize);
  104. stream.Seek(0, SeekOrigin.Begin);
  105. }
  106. }
  107. catch (Exception e)
  108. {
  109. LOG.Error(e.Message);
  110. return false;
  111. }
  112. return true;
  113. }
  114. /// <summary>
  115. /// Serialize the supplied object To Xml stream
  116. /// </summary>
  117. /// <param name="valueToSerializeToMemoryStream"></param>
  118. /// <returns></returns>
  119. public static string SerializeObjectToXml(object valueToSerializeToMemoryStream)
  120. {
  121. using (var memStream = SerializeObjectToMemoryStream(valueToSerializeToMemoryStream))
  122. using (var reader = new StreamReader(memStream))
  123. {
  124. return reader.ReadToEnd();
  125. }
  126. }
  127. /// <summary>
  128. /// Serializes an object into a Xml file.
  129. /// </summary>
  130. /// <param name="fullFileName"></param>
  131. /// <param name="valueToSerializeToFile"></param>
  132. /// <returns></returns>
  133. public static bool SerializeObjectToXmlFile(string fullFileName, object valueToSerializeToFile)
  134. {
  135. try
  136. {
  137. using (FileStream fs = new FileStream(fullFileName, FileMode.Create))//file existed, use "FileMode.CreateNew" will cause exception
  138. {
  139. using (MemoryStream ms = SerializeObjectToMemoryStream(valueToSerializeToFile))
  140. {
  141. ms.WriteTo(fs);
  142. ms.Close();
  143. }
  144. fs.Close();
  145. }
  146. }
  147. catch (Exception e)
  148. {
  149. LOG.Error(e.Message);
  150. return false;
  151. }
  152. return true;
  153. }
  154. /// <summary>
  155. /// Deserialize supplied stream using XmlSerializer
  156. /// </summary>
  157. /// <typeparam name="T"></typeparam>
  158. /// <param name="stream"></param>
  159. /// <returns></returns>
  160. public static T DeserializeObjectFromStream<T>(Stream stream)
  161. {
  162. var serializer = new XmlSerializer(typeof(T));
  163. var retVal = (T)serializer.Deserialize(stream);
  164. return retVal;
  165. }
  166. /// <summary>
  167. /// Convert binary file content to object
  168. /// </summary>
  169. /// <typeparam name="T"></typeparam>
  170. /// <param name="binFilePath"></param>
  171. /// <returns></returns>
  172. public static T DeserializeObjectFromBinaryFile<T>(string binFilePath)
  173. {
  174. T obj = default(T);
  175. using (FileStream fs = new FileStream(binFilePath, FileMode.OpenOrCreate))
  176. {
  177. obj = (T)DeserializeObjectFromBinaryStream(fs);
  178. }
  179. return obj;
  180. }
  181. /// <summary>
  182. /// Deserialize supplied stream using BinaryFormatter
  183. /// </summary>
  184. /// <param name="stream"></param>
  185. /// <returns></returns>
  186. public static object DeserializeObjectFromBinaryStream(Stream stream)
  187. {
  188. IFormatter formatter = new BinaryFormatter();
  189. var retVal = formatter.Deserialize(stream);
  190. return retVal;
  191. }
  192. /// <summary>
  193. /// Deserialize supplied stream using XmlSerializer to specified type of object
  194. /// </summary>
  195. /// <param name="stream"></param>
  196. /// <param name="typeOfObject"></param>
  197. /// <returns></returns>
  198. public static object DeserializeObjectFromStream(Stream stream, Type typeOfObject)
  199. {
  200. try
  201. {
  202. var serializer = new XmlSerializer(typeOfObject);
  203. object retVal = serializer.Deserialize(stream);
  204. return retVal;
  205. }
  206. catch (Exception ex)
  207. {
  208. LOG.Error(string.Format("界面发序列化数据出错:\n函数名:{0}\n串行数据内容:{1}",
  209. System.Reflection.MethodInfo.GetCurrentMethod().Name,
  210. stream.ToString()), ex);
  211. throw;
  212. }
  213. }
  214. /// <summary>
  215. /// Deserialize supplied stream using XmlSerializer to specified tyep of object
  216. /// </summary>
  217. /// <param name="stream"></param>
  218. /// <param name="typeOfObject"></param>
  219. /// <param name="types"></param>
  220. /// <returns></returns>
  221. public static object DeserializeObjectFromStream(Stream stream, Type typeOfObject, Type[] types)
  222. {
  223. types = RemoveDuplicateType(typeOfObject, types);
  224. var serializer = new XmlSerializer(typeOfObject, types);
  225. object retVal = serializer.Deserialize(stream);
  226. return retVal;
  227. }
  228. /// <summary>
  229. /// Convert supplied string to xml stream, then deserialize the xml stream to specified type of object
  230. /// </summary>
  231. /// <param name="xml"></param>
  232. /// <param name="typeToDeserialize"></param>
  233. /// <returns></returns>
  234. public static object DeserializeObjectFromXml(string xml, Type typeToDeserialize)
  235. {
  236. if (string.IsNullOrWhiteSpace(xml))
  237. {
  238. return null;
  239. }
  240. using (var memoryStream = new MemoryStream())
  241. {
  242. var xmlDoc = new XmlDocument();
  243. xmlDoc.LoadXml(xml);
  244. xmlDoc.Save(memoryStream);
  245. memoryStream.Seek(0, SeekOrigin.Begin);
  246. return DeserializeObjectFromStream(memoryStream, typeToDeserialize);
  247. }
  248. }
  249. /// <summary>
  250. /// Convert xml file content to object
  251. /// </summary>
  252. /// <typeparam name="T"></typeparam>
  253. /// <param name="xmlFilePath"></param>
  254. /// <returns></returns>
  255. public static T DeserializeObjectFromXmlFile<T>(string xmlFilePath)
  256. {
  257. T obj = default(T);
  258. FileInfo fi = new FileInfo(xmlFilePath);
  259. if (!fi.Exists) return obj;
  260. using (StreamReader reader = new StreamReader(xmlFilePath))
  261. {
  262. if (string.IsNullOrWhiteSpace(reader.ReadToEnd())) return obj;
  263. }
  264. using (FileStream fs = new FileStream(xmlFilePath, FileMode.Open))
  265. {
  266. obj = DeserializeObjectFromStream<T>(fs);
  267. }
  268. return obj;
  269. }
  270. }
  271. }