ObjectSerializer.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 DataAnalysisControl.Core;
  13. namespace Aitex.DataAnalysis.Core
  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. /// <summary>
  49. /// Serialize the supplied object To binary stream, SeekOrigin set to Begin.
  50. /// </summary>
  51. /// <param name="valueToSerializeToMemoryStream"></param>
  52. /// <returns></returns>
  53. public static MemoryStream SerializeObjectToBinaryStream(object valueToSerializeToMemoryStream)
  54. {
  55. // Converts object [objectToSerialize] of type [typeOfObjectBeingSerialized] to a memory stream
  56. var retVal = new MemoryStream();
  57. IFormatter formatter = new BinaryFormatter();
  58. formatter.Serialize(retVal, valueToSerializeToMemoryStream);
  59. retVal.Seek(0, SeekOrigin.Begin);
  60. return retVal;
  61. }
  62. /// <summary>
  63. /// Serializes an object into a file using binary formatter.
  64. /// </summary>
  65. /// <param name="fullFileName"></param>
  66. /// <param name="valueToSerialize"></param>
  67. /// <returns></returns>
  68. public static bool SerializeObjectToBinaryFile(string fullFileName, object valueToSerialize)
  69. {
  70. try
  71. {
  72. using (FileStream stream = new FileStream(fullFileName, FileMode.OpenOrCreate))
  73. {
  74. IFormatter formatter = new BinaryFormatter();
  75. formatter.Serialize(stream, valueToSerialize);
  76. stream.Seek(0, SeekOrigin.Begin);
  77. }
  78. }
  79. catch (Exception ex)
  80. {
  81. CONTEXT.WriteLog(ex);
  82. return false;
  83. }
  84. return true;
  85. }
  86. /// <summary>
  87. /// Serialize the supplied object To Xml stream
  88. /// </summary>
  89. /// <param name="valueToSerializeToMemoryStream"></param>
  90. /// <returns></returns>
  91. public static string SerializeObjectToXml(object valueToSerializeToMemoryStream)
  92. {
  93. using (var memStream = SerializeObjectToMemoryStream(valueToSerializeToMemoryStream))
  94. using (var reader = new StreamReader(memStream))
  95. {
  96. return reader.ReadToEnd();
  97. }
  98. }
  99. /// <summary>
  100. /// Serializes an object into a Xml file.
  101. /// </summary>
  102. /// <param name="fullFileName"></param>
  103. /// <param name="valueToSerializeToFile"></param>
  104. /// <returns></returns>
  105. public static bool SerializeObjectToXmlFile(string fullFileName, object valueToSerializeToFile)
  106. {
  107. try
  108. {
  109. using(FileStream fs = new FileStream(fullFileName, FileMode.Create))//file existed, use "FileMode.CreateNew" will cause exception
  110. {
  111. using (MemoryStream ms = SerializeObjectToMemoryStream(valueToSerializeToFile))
  112. {
  113. ms.WriteTo(fs);
  114. ms.Close();
  115. }
  116. fs.Close();
  117. }
  118. }
  119. catch (Exception e)
  120. {
  121. CONTEXT.WriteLog(e);
  122. return false;
  123. }
  124. return true;
  125. }
  126. public static T DeserializeObjectFromStream<T>(Stream stream)
  127. {
  128. var serializer = new XmlSerializer(typeof(T));
  129. var retVal = (T)serializer.Deserialize(stream);
  130. return retVal;
  131. }
  132. /// <summary>
  133. /// Convert binary file content to object
  134. /// </summary>
  135. /// <typeparam name="T"></typeparam>
  136. /// <param name="binFilePath"></param>
  137. /// <returns></returns>
  138. public static T DeserializeObjectFromBinaryFile<T>(string binFilePath)
  139. {
  140. T obj = default(T);
  141. using (FileStream fs = new FileStream(binFilePath, FileMode.OpenOrCreate))
  142. {
  143. obj = (T)DeserializeObjectFromBinaryStream(fs);
  144. }
  145. return obj;
  146. }
  147. /// <summary>
  148. /// Deserialize supplied stream using BinaryFormatter
  149. /// </summary>
  150. /// <param name="stream"></param>
  151. /// <returns></returns>
  152. public static object DeserializeObjectFromBinaryStream(Stream stream)
  153. {
  154. IFormatter formatter = new BinaryFormatter();
  155. var retVal = formatter.Deserialize(stream);
  156. return retVal;
  157. }
  158. public static object DeserializeObjectFromStream(Stream stream, Type typeOfObject)
  159. {
  160. try
  161. {
  162. var serializer = new XmlSerializer(typeOfObject);
  163. object retVal = serializer.Deserialize(stream);
  164. return retVal;
  165. }
  166. catch(Exception ex)
  167. {
  168. CONTEXT.WriteLog(ex, string.Format("界面发序列化数据出错:\n函数名:{0}\n串行数据内容:{1}",
  169. System.Reflection.MethodInfo.GetCurrentMethod().Name,
  170. stream.ToString()));
  171. throw;
  172. }
  173. }
  174. /// <summary>
  175. /// Convert supplied string to xml stream, then deserialize the xml stream to specified type of object
  176. /// </summary>
  177. /// <param name="xml"></param>
  178. /// <param name="typeToDeserialize"></param>
  179. /// <returns></returns>
  180. public static object DeserializeObjectFromXml(string xml, Type typeToDeserialize)
  181. {
  182. if (string.IsNullOrWhiteSpace(xml))
  183. {
  184. return null;
  185. }
  186. using (var memoryStream = new MemoryStream())
  187. {
  188. var xmlDoc = new XmlDocument();
  189. xmlDoc.LoadXml(xml);
  190. xmlDoc.Save(memoryStream);
  191. memoryStream.Seek(0, SeekOrigin.Begin);
  192. return DeserializeObjectFromStream(memoryStream, typeToDeserialize);
  193. }
  194. }
  195. /// <summary>
  196. /// Convert xml file content to object
  197. /// </summary>
  198. /// <typeparam name="T"></typeparam>
  199. /// <param name="xmlFilePath"></param>
  200. /// <returns></returns>
  201. public static T DeserializeObjectFromXmlFile<T>(string xmlFilePath)
  202. {
  203. T obj = default(T);
  204. FileInfo fi = new FileInfo(xmlFilePath);
  205. if (!fi.Exists) return obj;
  206. using (StreamReader reader = new StreamReader(xmlFilePath))
  207. {
  208. if (string.IsNullOrWhiteSpace(reader.ReadToEnd())) return obj;
  209. }
  210. using (FileStream fs = new FileStream(xmlFilePath, FileMode.Open))
  211. {
  212. obj = DeserializeObjectFromStream<T>(fs);
  213. }
  214. return obj;
  215. }
  216. }
  217. }