ObjectSerializer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. //todo here always throw exception sometimes
  163. var serializer = new XmlSerializer(typeof(T));
  164. var retVal = (T)serializer.Deserialize(stream);
  165. return retVal;
  166. }
  167. /// <summary>
  168. /// Convert binary file content to object
  169. /// </summary>
  170. /// <typeparam name="T"></typeparam>
  171. /// <param name="binFilePath"></param>
  172. /// <returns></returns>
  173. public static T DeserializeObjectFromBinaryFile<T>(string binFilePath)
  174. {
  175. T obj = default(T);
  176. using (FileStream fs = new FileStream(binFilePath, FileMode.OpenOrCreate))
  177. {
  178. obj = (T)DeserializeObjectFromBinaryStream(fs);
  179. }
  180. return obj;
  181. }
  182. /// <summary>
  183. /// Deserialize supplied stream using BinaryFormatter
  184. /// </summary>
  185. /// <param name="stream"></param>
  186. /// <returns></returns>
  187. public static object DeserializeObjectFromBinaryStream(Stream stream)
  188. {
  189. IFormatter formatter = new BinaryFormatter();
  190. var retVal = formatter.Deserialize(stream);
  191. return retVal;
  192. }
  193. /// <summary>
  194. /// Deserialize supplied stream using XmlSerializer to specified type of object
  195. /// </summary>
  196. /// <param name="stream"></param>
  197. /// <param name="typeOfObject"></param>
  198. /// <returns></returns>
  199. public static object DeserializeObjectFromStream(Stream stream, Type typeOfObject)
  200. {
  201. try
  202. {
  203. var serializer = new XmlSerializer(typeOfObject);
  204. object retVal = serializer.Deserialize(stream);
  205. return retVal;
  206. }
  207. catch (Exception ex)
  208. {
  209. LOG.Error(string.Format("界面发序列化数据出错:\n函数名:{0}\n串行数据内容:{1}",
  210. System.Reflection.MethodInfo.GetCurrentMethod().Name,
  211. stream.ToString()), ex);
  212. throw;
  213. }
  214. }
  215. /// <summary>
  216. /// Deserialize supplied stream using XmlSerializer to specified tyep of object
  217. /// </summary>
  218. /// <param name="stream"></param>
  219. /// <param name="typeOfObject"></param>
  220. /// <param name="types"></param>
  221. /// <returns></returns>
  222. public static object DeserializeObjectFromStream(Stream stream, Type typeOfObject, Type[] types)
  223. {
  224. types = RemoveDuplicateType(typeOfObject, types);
  225. var serializer = new XmlSerializer(typeOfObject, types);
  226. object retVal = serializer.Deserialize(stream);
  227. return retVal;
  228. }
  229. /// <summary>
  230. /// Convert supplied string to xml stream, then deserialize the xml stream to specified type of object
  231. /// </summary>
  232. /// <param name="xml"></param>
  233. /// <param name="typeToDeserialize"></param>
  234. /// <returns></returns>
  235. public static object DeserializeObjectFromXml(string xml, Type typeToDeserialize)
  236. {
  237. if (string.IsNullOrWhiteSpace(xml))
  238. {
  239. return null;
  240. }
  241. using (var memoryStream = new MemoryStream())
  242. {
  243. var xmlDoc = new XmlDocument();
  244. xmlDoc.LoadXml(xml);
  245. xmlDoc.Save(memoryStream);
  246. memoryStream.Seek(0, SeekOrigin.Begin);
  247. return DeserializeObjectFromStream(memoryStream, typeToDeserialize);
  248. }
  249. }
  250. /// <summary>
  251. /// Convert xml file content to object
  252. /// </summary>
  253. /// <typeparam name="T"></typeparam>
  254. /// <param name="xmlFilePath"></param>
  255. /// <returns></returns>
  256. public static T DeserializeObjectFromXmlFile<T>(string xmlFilePath)
  257. {
  258. T obj = default(T);
  259. FileInfo fi = new FileInfo(xmlFilePath);
  260. if (!fi.Exists) return obj;
  261. using (StreamReader reader = new StreamReader(xmlFilePath))
  262. {
  263. if (string.IsNullOrWhiteSpace(reader.ReadToEnd())) return obj;
  264. }
  265. using (FileStream fs = new FileStream(xmlFilePath, FileMode.Open))
  266. {
  267. obj = DeserializeObjectFromStream<T>(fs);
  268. }
  269. return obj;
  270. }
  271. }
  272. }