[C#] C#编写的序列化通用类代码 →→→→→进入此内容的聊天室

来自 , 2021-01-01, 写在 C#, 查看 111 次.
URL http://www.code666.cn/view/3cfacd1b
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Runtime.Serialization.Formatters.Binary;
  5. using System.Runtime.Serialization.Formatters.Soap;
  6. using System.Text;
  7. using System.Xml;
  8. using System.Xml.Serialization;
  9.  
  10.  
  11. namespace PlatForm.Utilities
  12. {
  13.     public enum SerializedType : ushort
  14.     {
  15.         ByteArray = 0,
  16.         Object = 1,
  17.         String = 2,
  18.         Datetime = 3,
  19.         Bool = 4,
  20.         //SByte     = 5, //Makes no sense.
  21.         Byte = 6,
  22.         Short = 7,
  23.         UShort = 8,
  24.         Int = 9,
  25.         UInt = 10,
  26.         Long = 11,
  27.         ULong = 12,
  28.         Float = 13,
  29.         Double = 14,
  30.  
  31.         CompressedByteArray = 255,
  32.         CompressedObject = 256,
  33.         CompressedString = 257,
  34.     }
  35.  
  36.     public class SerializeHelper
  37.     {
  38.         public SerializeHelper()
  39.         { }
  40.  
  41.         #region XML序列化
  42.         /// <summary>
  43.         /// 文件化XML序列化
  44.         /// </summary>
  45.         /// <param name="obj">对象</param>
  46.         /// <param name="filename">文件路径</param>
  47.         public static void Save(object obj, string filename)
  48.         {
  49.             FileStream fs = null;
  50.             try
  51.             {
  52.                 fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
  53.                 XmlSerializer serializer = new XmlSerializer(obj.GetType());
  54.                 serializer.Serialize(fs, obj);
  55.             }
  56.             catch (Exception ex)
  57.             {
  58.                 throw ex;
  59.             }
  60.             finally
  61.             {
  62.                 if (fs != null) fs.Close();
  63.             }
  64.         }
  65.  
  66.         /// <summary>
  67.         /// 文件化XML反序列化
  68.         /// </summary>
  69.         /// <param name="type">对象类型</param>
  70.         /// <param name="filename">文件路径</param>
  71.         public static object Load(Type type, string filename)
  72.         {
  73.             FileStream fs = null;
  74.             try
  75.             {
  76.                 fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  77.                 XmlSerializer serializer = new XmlSerializer(type);
  78.                 return serializer.Deserialize(fs);
  79.             }
  80.             catch (Exception ex)
  81.             {
  82.                 throw ex;
  83.             }
  84.             finally
  85.             {
  86.                 if (fs != null) fs.Close();
  87.             }
  88.         }
  89.  
  90.         /// <summary>
  91.         /// 文本化XML序列化
  92.         /// </summary>
  93.         /// <param name="item">对象</param>
  94.         public string ToXml<T>(T item)
  95.         {
  96.             XmlSerializer serializer = new XmlSerializer(item.GetType());
  97.             StringBuilder sb = new StringBuilder();
  98.             using (XmlWriter writer = XmlWriter.Create(sb))
  99.             {
  100.                 serializer.Serialize(writer, item);
  101.                 return sb.ToString();
  102.             }
  103.         }
  104.  
  105.         /// <summary>
  106.         /// 文本化XML反序列化
  107.         /// </summary>
  108.         /// <param name="str">字符串序列</param>
  109.         public T FromXml<T>(string str)
  110.         {
  111.             XmlSerializer serializer = new XmlSerializer(typeof(T));
  112.             using (XmlReader reader = new XmlTextReader(new StringReader(str)))
  113.             {
  114.                 return (T)serializer.Deserialize(reader);
  115.             }
  116.         }
  117.         #endregion        
  118.  
  119.         #region SoapFormatter序列化
  120.         /// <summary>
  121.         /// SoapFormatter序列化
  122.         /// </summary>
  123.         /// <param name="item">对象</param>
  124.         public static string ToSoap<T>(T item)
  125.         {
  126.             SoapFormatter formatter = new SoapFormatter();
  127.             using (MemoryStream ms = new MemoryStream())
  128.             {
  129.                 formatter.Serialize(ms, item);
  130.                 ms.Position = 0;
  131.                 XmlDocument xmlDoc = new XmlDocument();
  132.                 xmlDoc.Load(ms);
  133.                 return xmlDoc.InnerXml;
  134.             }
  135.         }
  136.  
  137.         /// <summary>
  138.         /// SoapFormatter反序列化
  139.         /// </summary>
  140.         /// <param name="str">字符串序列</param>
  141.         public static T FromSoap<T>(string str)
  142.         {
  143.             XmlDocument xmlDoc = new XmlDocument();
  144.             xmlDoc.LoadXml(str);
  145.             SoapFormatter formatter = new SoapFormatter();
  146.             using (MemoryStream ms = new MemoryStream())
  147.             {
  148.                 xmlDoc.Save(ms);
  149.                 ms.Position = 0;
  150.                 return (T)formatter.Deserialize(ms);
  151.             }
  152.         }
  153.         #endregion
  154.  
  155.         #region BinaryFormatter序列化
  156.         /// <summary>
  157.         /// BinaryFormatter序列化
  158.         /// </summary>
  159.         /// <param name="item">对象</param>
  160.         public static string ToBinary<T>(T item)
  161.         {
  162.             BinaryFormatter formatter = new BinaryFormatter();
  163.             using (MemoryStream ms = new MemoryStream())
  164.             {
  165.                 formatter.Serialize(ms, item);
  166.                 ms.Position = 0;
  167.                 byte[] bytes = ms.ToArray();
  168.                 StringBuilder sb = new StringBuilder();
  169.                 foreach (byte bt in bytes)
  170.                 {
  171.                     sb.Append(string.Format("{0:X2}", bt));
  172.                 }
  173.                 return sb.ToString();
  174.             }
  175.         }
  176.  
  177.         /// <summary>
  178.         /// BinaryFormatter反序列化
  179.         /// </summary>
  180.         /// <param name="str">字符串序列</param>
  181.         public static T FromBinary<T>(string str)
  182.         {
  183.             int intLen = str.Length / 2;
  184.             byte[] bytes = new byte[intLen];
  185.             for (int i = 0; i < intLen; i++)
  186.             {
  187.                 int ibyte = Convert.ToInt32(str.Substring(i * 2, 2), 16);
  188.                 bytes[i] = (byte)ibyte;
  189.             }
  190.             BinaryFormatter formatter = new BinaryFormatter();
  191.             using (MemoryStream ms = new MemoryStream(bytes))
  192.             {
  193.                 return (T)formatter.Deserialize(ms);
  194.             }
  195.         }
  196.         #endregion
  197.  
  198.         /// <summary>
  199.         /// 将对象序列化为二进制字节
  200.         /// </summary>
  201.         /// <param name="obj">待序列化的对象</param>
  202.         /// <returns></returns>
  203.         public static byte[] SerializeToBinary(object obj)
  204.         {
  205.             byte[] bytes = new byte[2500];
  206.             using (MemoryStream memoryStream = new MemoryStream())
  207.             {
  208.                 BinaryFormatter bformatter = new BinaryFormatter();
  209.                 bformatter.Serialize(memoryStream, obj);
  210.                 memoryStream.Seek(0, 0);
  211.  
  212.                 if (memoryStream.Length > bytes.Length)
  213.                 {
  214.                     bytes = new byte[memoryStream.Length];
  215.                 }
  216.                 bytes = memoryStream.ToArray();
  217.             }
  218.             return bytes;
  219.         }
  220.  
  221.         /// <summary>
  222.         /// 从二进制字节中反序列化为对象
  223.         /// </summary>
  224.         /// <param name="type">对象的类型</param>
  225.         /// <param name="bytes">字节数组</param>
  226.         /// <returns>反序列化后得到的对象</returns>
  227.         public static object DeserializeFromBinary(Type type, byte[] bytes)
  228.         {
  229.             object result = new object();
  230.             using (MemoryStream memoryStream = new MemoryStream(bytes))
  231.             {
  232.                 BinaryFormatter serializer = new BinaryFormatter();
  233.                 result = serializer.Deserialize(memoryStream);
  234.             }
  235.  
  236.             return result;
  237.         }
  238.  
  239.         /// <summary>
  240.         /// 将文件对象序列化到文件中
  241.         /// </summary>
  242.         /// <param name="obj">待序列化的对象</param>
  243.         /// <param name="path">文件路径</param>
  244.         /// <param name="fileMode">文件打开模式</param>
  245.         public static void SerializeToBinary(object obj, string path, FileMode fileMode)
  246.         {
  247.             using (FileStream fs = new FileStream(path, fileMode))
  248.             {
  249.                 // Construct a BinaryFormatter and use it to serialize the data to the stream.
  250.                 BinaryFormatter formatter = new BinaryFormatter();
  251.                 formatter.Serialize(fs, obj);
  252.             }
  253.         }
  254.  
  255.         /// <summary>
  256.         /// 将文件对象序列化到文件中
  257.         /// </summary>
  258.         /// <param name="obj">待序列化的对象</param>
  259.         /// <param name="path">文件路径</param>
  260.         public static void SerializeToBinary(object obj, string path)
  261.         {
  262.             SerializeToBinary(obj, path, FileMode.Create);
  263.         }
  264.  
  265.         /// <summary>
  266.         /// 从二进制文件中反序列化为对象
  267.         /// </summary>
  268.         /// <param name="type">对象的类型</param>
  269.         /// <param name="path">二进制文件路径</param>
  270.         /// <returns>反序列化后得到的对象</returns>
  271.         public static object DeserializeFromBinary(Type type, string path)
  272.         {
  273.             object result = new object();
  274.             using (FileStream fileStream = new FileStream(path, FileMode.Open))
  275.             {
  276.                 BinaryFormatter serializer = new BinaryFormatter();
  277.                 result = serializer.Deserialize(fileStream);
  278.             }
  279.  
  280.             return result;
  281.         }
  282.  
  283.         /// <summary>
  284.         /// 获取对象的转换为二进制的字节大小
  285.         /// </summary>
  286.         /// <param name="obj"></param>
  287.         /// <returns></returns>
  288.         public static long GetByteSize(object obj)
  289.         {
  290.             long result;
  291.             BinaryFormatter bFormatter = new BinaryFormatter();
  292.             using (MemoryStream stream = new MemoryStream())
  293.             {
  294.                 bFormatter.Serialize(stream, obj);
  295.                 result = stream.Length;
  296.             }
  297.             return result;
  298.         }
  299.  
  300.         /// <summary>
  301.         /// 克隆一个对象
  302.         /// </summary>
  303.         /// <param name="obj">待克隆的对象</param>
  304.         /// <returns>克隆的一个新的对象</returns>
  305.         public static object Clone(object obj)
  306.         {
  307.             object cloned = null;
  308.             BinaryFormatter bFormatter = new BinaryFormatter();
  309.             using (MemoryStream memoryStream = new MemoryStream())
  310.             {
  311.                 try
  312.                 {
  313.                     bFormatter.Serialize(memoryStream, obj);
  314.                     memoryStream.Seek(0, SeekOrigin.Begin);
  315.                     cloned = bFormatter.Deserialize(memoryStream);
  316.                 }
  317.                 catch //(Exception e)
  318.                 {
  319.                     ;
  320.                 }
  321.             }
  322.  
  323.             return cloned;
  324.         }
  325.  
  326.         /// <summary>
  327.         /// 从文件中读取文本内容
  328.         /// </summary>
  329.         /// <param name="path">文件路径</param>
  330.         /// <returns>文件的内容</returns>
  331.         public static string ReadFile(string path)
  332.         {
  333.             string content = string.Empty;
  334.             using (StreamReader reader = new StreamReader(path))
  335.             {
  336.                 content = reader.ReadToEnd();
  337.             }
  338.  
  339.             return content;
  340.         }
  341.  
  342.         public static byte[] Serialize(object value, out SerializedType type, uint compressionThreshold)
  343.         {
  344.             byte[] bytes;
  345.             if (value is byte[])
  346.             {
  347.                 bytes = (byte[])value;
  348.                 type = SerializedType.ByteArray;
  349.                 if (bytes.Length > compressionThreshold)
  350.                 {
  351.                     bytes = compress(bytes);
  352.                     type = SerializedType.CompressedByteArray;
  353.                 }
  354.             }
  355.             else if (value is string)
  356.             {
  357.                 bytes = Encoding.UTF8.GetBytes((string)value);
  358.                 type = SerializedType.String;
  359.                 if (bytes.Length > compressionThreshold)
  360.                 {
  361.                     bytes = compress(bytes);
  362.                     type = SerializedType.CompressedString;
  363.                 }
  364.             }
  365.             else if (value is DateTime)
  366.             {
  367.                 bytes = BitConverter.GetBytes(((DateTime)value).Ticks);
  368.                 type = SerializedType.Datetime;
  369.             }
  370.             else if (value is bool)
  371.             {
  372.                 bytes = new byte[] { (byte)((bool)value ? 1 : 0) };
  373.                 type = SerializedType.Bool;
  374.             }
  375.             else if (value is byte)
  376.             {
  377.                 bytes = new byte[] { (byte)value };
  378.                 type = SerializedType.Byte;
  379.             }
  380.             else if (value is short)
  381.             {
  382.                 bytes = BitConverter.GetBytes((short)value);
  383.                 type = SerializedType.Short;
  384.             }
  385.             else if (value is ushort)
  386.             {
  387.                 bytes = BitConverter.GetBytes((ushort)value);
  388.                 type = SerializedType.UShort;
  389.             }
  390.             else if (value is int)
  391.             {
  392.                 bytes = BitConverter.GetBytes((int)value);
  393.                 type = SerializedType.Int;
  394.             }
  395.             else if (value is uint)
  396.             {
  397.                 bytes = BitConverter.GetBytes((uint)value);
  398.                 type = SerializedType.UInt;
  399.             }
  400.             else if (value is long)
  401.             {
  402.                 bytes = BitConverter.GetBytes((long)value);
  403.                 type = SerializedType.Long;
  404.             }
  405.             else if (value is ulong)
  406.             {
  407.                 bytes = BitConverter.GetBytes((ulong)value);
  408.                 type = SerializedType.ULong;
  409.             }
  410.             else if (value is float)
  411.             {
  412.                 bytes = BitConverter.GetBytes((float)value);
  413.                 type = SerializedType.Float;
  414.             }
  415.             else if (value is double)
  416.             {
  417.                 bytes = BitConverter.GetBytes((double)value);
  418.                 type = SerializedType.Double;
  419.             }
  420.             else
  421.             {
  422.                 //Object
  423.                 using (MemoryStream ms = new MemoryStream())
  424.                 {
  425.                     new BinaryFormatter().Serialize(ms, value);
  426.                     bytes = ms.GetBuffer();
  427.                     type = SerializedType.Object;
  428.                     if (bytes.Length > compressionThreshold)
  429.                     {
  430.                         bytes = compress(bytes);
  431.                         type = SerializedType.CompressedObject;
  432.                     }
  433.                 }
  434.             }
  435.             return bytes;
  436.         }
  437.  
  438.         private static byte[] compress(byte[] bytes)
  439.         {
  440.             using (MemoryStream ms = new MemoryStream())
  441.             {
  442.                 using (DeflateStream gzs = new DeflateStream(ms, CompressionMode.Compress, false))
  443.                 {
  444.                     gzs.Write(bytes, 0, bytes.Length);
  445.                 }
  446.                 ms.Close();
  447.                 return ms.GetBuffer();
  448.             }
  449.         }
  450.  
  451.         private static byte[] decompress(byte[] bytes)
  452.         {
  453.             using (MemoryStream ms = new MemoryStream(bytes, false))
  454.             {
  455.                 using (DeflateStream gzs = new DeflateStream(ms, CompressionMode.Decompress, false))
  456.                 {
  457.                     using (MemoryStream dest = new MemoryStream())
  458.                     {
  459.                         byte[] tmp = new byte[bytes.Length];
  460.                         int read;
  461.                         while ((read = gzs.Read(tmp, 0, tmp.Length)) != 0)
  462.                         {
  463.                             dest.Write(tmp, 0, read);
  464.                         }
  465.                         dest.Close();
  466.                         return dest.GetBuffer();
  467.                     }
  468.                 }
  469.             }
  470.         }
  471.  
  472.         public static object DeSerialize(byte[] bytes, SerializedType type)
  473.         {
  474.             switch (type)
  475.             {
  476.                 case SerializedType.String:
  477.                     return Encoding.UTF8.GetString(bytes);
  478.                 case SerializedType.Datetime:
  479.                     return new DateTime(BitConverter.ToInt64(bytes, 0));
  480.                 case SerializedType.Bool:
  481.                     return bytes[0] == 1;
  482.                 case SerializedType.Byte:
  483.                     return bytes[0];
  484.                 case SerializedType.Short:
  485.                     return BitConverter.ToInt16(bytes, 0);
  486.                 case SerializedType.UShort:
  487.                     return BitConverter.ToUInt16(bytes, 0);
  488.                 case SerializedType.Int:
  489.                     return BitConverter.ToInt32(bytes, 0);
  490.                 case SerializedType.UInt:
  491.                     return BitConverter.ToUInt32(bytes, 0);
  492.                 case SerializedType.Long:
  493.                     return BitConverter.ToInt64(bytes, 0);
  494.                 case SerializedType.ULong:
  495.                     return BitConverter.ToUInt64(bytes, 0);
  496.                 case SerializedType.Float:
  497.                     return BitConverter.ToSingle(bytes, 0);
  498.                 case SerializedType.Double:
  499.                     return BitConverter.ToDouble(bytes, 0);
  500.                 case SerializedType.Object:
  501.                     using (MemoryStream ms = new MemoryStream(bytes))
  502.                     {
  503.                         return new BinaryFormatter().Deserialize(ms);
  504.                     }
  505.                 case SerializedType.CompressedByteArray:
  506.                     return DeSerialize(decompress(bytes), SerializedType.ByteArray);
  507.                 case SerializedType.CompressedString:
  508.                     return DeSerialize(decompress(bytes), SerializedType.String);
  509.                 case SerializedType.CompressedObject:
  510.                     return DeSerialize(decompress(bytes), SerializedType.Object);
  511.                 case SerializedType.ByteArray:
  512.                 default:
  513.                     return bytes;
  514.             }
  515.         }
  516.     }  
  517. }
  518. //csharp/6783

回复 "C#编写的序列化通用类代码"

这儿你可以回复上面这条便签

captcha