This article describes the serialization general class implemented by C#. Share it for your reference. The details are as follows:
using System; using ; using ; using ; using ; using ; using ; using ; namespace { public enum SerializedType : ushort { ByteArray = 0, Object = 1, String = 2, Datetime = 3, Bool = 4, //SByte = 5, //Makes no sense. Byte = 6, Short = 7, UShort = 8, Int = 9, UInt = 10, Long = 11, ULong = 12, Float = 13, Double = 14, CompressedByteArray = 255, CompressedObject = 256, CompressedString = 257, } public class SerializeHelper { public SerializeHelper() { } #region XML Serialization /// <summary> /// Filed XML Serialization /// </summary> /// <param name="obj">Object</param> /// <param name="filename">File path</param> public static void Save(object obj, string filename) { FileStream fs = null; try { fs = new FileStream(filename, , , ); XmlSerializer serializer = new XmlSerializer(()); (fs, obj); } catch (Exception ex) { throw ex; } finally { if (fs != null) (); } } /// <summary> /// Filed XML deserialization /// </summary> /// <param name="type">Object type</param> /// <param name="filename">File path</param> public static object Load(Type type, string filename) { FileStream fs = null; try { fs = new FileStream(filename, , , ); XmlSerializer serializer = new XmlSerializer(type); return (fs); } catch (Exception ex) { throw ex; } finally { if (fs != null) (); } } /// <summary> /// Textured XML Serialization /// </summary> /// <param name="item">Object</param> public string ToXml<T>(T item) { XmlSerializer serializer = new XmlSerializer(()); StringBuilder sb = new StringBuilder(); using (XmlWriter writer = (sb)) { (writer, item); return (); } } /// <summary> /// Textured XML deserialization /// </summary> /// <param name="str">Sequence of strings</param> public T FromXml<T>(string str) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (XmlReader reader = new XmlTextReader(new StringReader(str))) { return (T)(reader); } } #endregion #region SoapFormatter Serialization /// <summary> /// SoapFormatter Serialization /// </summary> /// <param name="item">Object</param> public static string ToSoap<T>(T item) { SoapFormatter formatter = new SoapFormatter(); using (MemoryStream ms = new MemoryStream()) { (ms, item); = 0; XmlDocument xmlDoc = new XmlDocument(); (ms); return ; } } /// <summary> /// SoapFormatter Deserialization /// </summary> /// <param name="str">Sequence of strings</param> public static T FromSoap<T>(string str) { XmlDocument xmlDoc = new XmlDocument(); (str); SoapFormatter formatter = new SoapFormatter(); using (MemoryStream ms = new MemoryStream()) { (ms); = 0; return (T)(ms); } } #endregion #region BinaryFormatter Serialization /// <summary> /// BinaryFormatter Serialization /// </summary> /// <param name="item">Object</param> public static string ToBinary<T>(T item) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { (ms, item); = 0; byte[] bytes = (); StringBuilder sb = new StringBuilder(); foreach (byte bt in bytes) { (("{0:X2}", bt)); } return (); } } /// <summary> /// BinaryFormatter Deserialization /// </summary> /// <param name="str">Sequence of strings</param> public static T FromBinary<T>(string str) { int intLen = / 2; byte[] bytes = new byte[intLen]; for (int i = 0; i < intLen; i++) { int ibyte = Convert.ToInt32((i * 2, 2), 16); bytes[i] = (byte)ibyte; } BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream(bytes)) { return (T)(ms); } } #endregion /// <summary> /// Serialize the object into binary bytes /// </summary> /// <param name="obj">Object to be serialized</param> /// <returns></returns> public static byte[] SerializeToBinary(object obj) { byte[] bytes = new byte[2500]; using (MemoryStream memoryStream = new MemoryStream()) { BinaryFormatter bformatter = new BinaryFormatter(); (memoryStream, obj); (0, 0); if ( > ) { bytes = new byte[]; } bytes = (); } return bytes; } /// <summary> /// Deserialize to an object from binary bytes /// </summary> /// <param name="type">Object type</param> /// <param name="bytes">Byte array</param> /// <returns>Object obtained after deserialization</returns> public static object DeserializeFromBinary(Type type, byte[] bytes) { object result = new object(); using (MemoryStream memoryStream = new MemoryStream(bytes)) { BinaryFormatter serializer = new BinaryFormatter(); result = (memoryStream); } return result; } /// <summary> /// Serialize file objects into file /// </summary> /// <param name="obj">Object to be serialized</param> /// <param name="path">File path</param> /// <param name="fileMode">File Open Mode</param> public static void SerializeToBinary(object obj, string path, FileMode fileMode) { using (FileStream fs = new FileStream(path, fileMode)) { // Construct a BinaryFormatter and use it to serialize the data to the stream. BinaryFormatter formatter = new BinaryFormatter(); (fs, obj); } } /// <summary> /// Serialize file objects into file /// </summary> /// <param name="obj">Object to be serialized</param> /// <param name="path">File path</param> public static void SerializeToBinary(object obj, string path) { SerializeToBinary(obj, path, ); } /// <summary> /// Deserialize to an object from a binary file /// </summary> /// <param name="type">Object type</param> /// <param name="path">Binary file path</param> /// <returns>Object obtained after deserialization</returns> public static object DeserializeFromBinary(Type type, string path) { object result = new object(); using (FileStream fileStream = new FileStream(path, )) { BinaryFormatter serializer = new BinaryFormatter(); result = (fileStream); } return result; } /// <summary> /// Get the byte size of the object converted to binary /// </summary> /// <param name="obj"></param> /// <returns></returns> public static long GetByteSize(object obj) { long result; BinaryFormatter bFormatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { (stream, obj); result = ; } return result; } /// <summary> ///Clone an object /// </summary> /// <param name="obj">Object to be cloned</param> /// <returns>Clone a new object</returns> public static object Clone(object obj) { object cloned = null; BinaryFormatter bFormatter = new BinaryFormatter(); using (MemoryStream memoryStream = new MemoryStream()) { try { (memoryStream, obj); (0, ); cloned = (memoryStream); } catch //(Exception e) { ; } } return cloned; } /// <summary> /// Read text content from a file /// </summary> /// <param name="path">File path</param> /// <returns>File content</returns> public static string ReadFile(string path) { string content = ; using (StreamReader reader = new StreamReader(path)) { content = (); } return content; } public static byte[] Serialize(object value, out SerializedType type, uint compressionThreshold) { byte[] bytes; if (value is byte[]) { bytes = (byte[])value; type = ; if ( > compressionThreshold) { bytes = compress(bytes); type = ; } } else if (value is string) { bytes = Encoding.((string)value); type = ; if ( > compressionThreshold) { bytes = compress(bytes); type = ; } } else if (value is DateTime) { bytes = (((DateTime)value).Ticks); type = ; } else if (value is bool) { bytes = new byte[] { (byte)((bool)value ? 1 : 0) }; type = ; } else if (value is byte) { bytes = new byte[] { (byte)value }; type = ; } else if (value is short) { bytes = ((short)value); type = ; } else if (value is ushort) { bytes = ((ushort)value); type = ; } else if (value is int) { bytes = ((int)value); type = ; } else if (value is uint) { bytes = ((uint)value); type = ; } else if (value is long) { bytes = ((long)value); type = ; } else if (value is ulong) { bytes = ((ulong)value); type = ; } else if (value is float) { bytes = ((float)value); type = ; } else if (value is double) { bytes = ((double)value); type = ; } else { //Object using (MemoryStream ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, value); bytes = (); type = ; if ( > compressionThreshold) { bytes = compress(bytes); type = ; } } } return bytes; } private static byte[] compress(byte[] bytes) { using (MemoryStream ms = new MemoryStream()) { using (DeflateStream gzs = new DeflateStream(ms, , false)) { (bytes, 0, ); } (); return (); } } private static byte[] decompress(byte[] bytes) { using (MemoryStream ms = new MemoryStream(bytes, false)) { using (DeflateStream gzs = new DeflateStream(ms, , false)) { using (MemoryStream dest = new MemoryStream()) { byte[] tmp = new byte[]; int read; while ((read = (tmp, 0, )) != 0) { (tmp, 0, read); } (); return (); } } } } public static object DeSerialize(byte[] bytes, SerializedType type) { switch (type) { case : return Encoding.(bytes); case : return new DateTime(BitConverter.ToInt64(bytes, 0)); case : return bytes[0] == 1; case : return bytes[0]; case : return BitConverter.ToInt16(bytes, 0); case : return BitConverter.ToUInt16(bytes, 0); case : return BitConverter.ToInt32(bytes, 0); case : return BitConverter.ToUInt32(bytes, 0); case : return BitConverter.ToInt64(bytes, 0); case : return BitConverter.ToUInt64(bytes, 0); case : return (bytes, 0); case : return (bytes, 0); case : using (MemoryStream ms = new MemoryStream(bytes)) { return new BinaryFormatter().Deserialize(ms); } case : return DeSerialize(decompress(bytes), ); case : return DeSerialize(decompress(bytes), ); case : return DeSerialize(decompress(bytes), ); case : default: return bytes; } } } }
I hope this article will be helpful to everyone's C# programming.