SoFunction
Updated on 2025-03-06

Serialized general class instances implemented by C#

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) ();
   }
  }
  /// &lt;summary&gt;
  /// Filed XML deserialization  /// &lt;/summary&gt;
  /// <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) ();
   }
  }
  /// &lt;summary&gt;
  /// Textured XML Serialization  /// &lt;/summary&gt;
  /// <param name="item">Object</param>  public string ToXml&lt;T&gt;(T item)
  {
   XmlSerializer serializer = new XmlSerializer(());
   StringBuilder sb = new StringBuilder();
   using (XmlWriter writer = (sb))
   {
    (writer, item);
    return ();
   }
  }
  /// &lt;summary&gt;
  /// Textured XML deserialization  /// &lt;/summary&gt;
  /// <param name="str">Sequence of strings</param>  public T FromXml&lt;T&gt;(string str)
  {
   XmlSerializer serializer = new XmlSerializer(typeof(T));
   using (XmlReader reader = new XmlTextReader(new StringReader(str)))
   {
    return (T)(reader);
   }
  }
  #endregion  
  #region SoapFormatter Serialization  /// &lt;summary&gt;
  /// SoapFormatter Serialization  /// &lt;/summary&gt;
  /// <param name="item">Object</param>  public static string ToSoap&lt;T&gt;(T item)
  {
   SoapFormatter formatter = new SoapFormatter();
   using (MemoryStream ms = new MemoryStream())
   {
    (ms, item);
     = 0;
    XmlDocument xmlDoc = new XmlDocument();
    (ms);
    return ;
   }
  }
  /// &lt;summary&gt;
  /// SoapFormatter Deserialization  /// &lt;/summary&gt;
  /// <param name="str">Sequence of strings</param>  public static T FromSoap&lt;T&gt;(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  /// &lt;summary&gt;
  /// BinaryFormatter Serialization  /// &lt;/summary&gt;
  /// <param name="item">Object</param>  public static string ToBinary&lt;T&gt;(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 ();
   }
  }
  /// &lt;summary&gt;
  /// BinaryFormatter Deserialization  /// &lt;/summary&gt;
  /// <param name="str">Sequence of strings</param>  public static T FromBinary&lt;T&gt;(string str)
  {
   int intLen =  / 2;
   byte[] bytes = new byte[intLen];
   for (int i = 0; i &lt; 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
  /// &lt;summary&gt;
  /// Serialize the object into binary bytes  /// &lt;/summary&gt;
  /// <param name="obj">Object to be serialized</param>  /// &lt;returns&gt;&lt;/returns&gt;
  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 ( &gt; )
    {
     bytes = new byte[];
    }
    bytes = ();
   }
   return bytes;
  }
  /// &lt;summary&gt;
  /// Deserialize to an object from binary bytes  /// &lt;/summary&gt;
  /// <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;
  }
  /// &lt;summary&gt;
  /// Serialize file objects into file  /// &lt;/summary&gt;
  /// <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);
   }
  }
  /// &lt;summary&gt;
  /// Serialize file objects into file  /// &lt;/summary&gt;
  /// <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, );
  }
  /// &lt;summary&gt;
  /// Deserialize to an object from a binary file  /// &lt;/summary&gt;
  /// <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;
  }
  /// &lt;summary&gt;
  /// Get the byte size of the object converted to binary  /// &lt;/summary&gt;
  /// &lt;param name="obj"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static long GetByteSize(object obj)
  {
   long result;
   BinaryFormatter bFormatter = new BinaryFormatter();
   using (MemoryStream stream = new MemoryStream())
   {
    (stream, obj);
    result = ;
   }
   return result;
  }
  /// &lt;summary&gt;
  ///Clone an object  /// &lt;/summary&gt;
  /// <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;
  }
  /// &lt;summary&gt;
  /// Read text content from a file  /// &lt;/summary&gt;
  /// <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 ( &gt; compressionThreshold)
    {
     bytes = compress(bytes);
     type = ;
    }
   }
   else if (value is string)
   {
    bytes = Encoding.((string)value);
    type = ;
    if ( &gt; 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 ( &gt; 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.