SoFunction
Updated on 2025-03-07

C# binary serialization example analysis

This article describes the method of C# binary serialization. Share it for your reference. The details are as follows:

using ;
using ;
namespace 
{
  public partial class Binary1 : 
  {
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    //Binary serialization is different from the XMLSerializer class, which only serializes public fields.    protected void Button1_Click(object sender, EventArgs e)
    {
      MyObject obj = new MyObject();
      obj.n1 = 1;
      obj.n2 = 24;
       = "Some String";
      IFormatter formatter = new BinaryFormatter();
      Stream stream = new FileStream("C:/", , , );
      (stream, obj);
      ();
    }
    [Serializable]
    public class MyObject
    {
      public int n1 = 0;
      public int n2 = 0;
      public String str = null;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
      IFormatter formatter = new BinaryFormatter();
      Stream stream = new FileStream("C:/", , , );
      MyObject obj = (MyObject)(stream);
      ();
      // Here's the proof.
      ("n1: {0}"+ obj.n1+"<br/>");
      ("n2: {0}" + obj.n2 + "<br/>");
      ("str: {0}" +  + "<br/>");
    }
    //The BinaryFormatter used above is very effective and generates a very concise byte stream.    //All objects serialized by this formatter can also be deserialized through this formatter, which makes this tool ideal for serializing objects that will be deserialized on the .NET Framework.    //It should be noted that the constructor is not called when deserializing an object.  This constraint is imposed on deserialization for performance reasons.    // However, this violates some common conventions between the runtime library and the object writer, and developers should make sure they understand the consequences when marking the object as serializable.    // If portability is required, switch to SoapFormatter.    //Simply use SoapFormatter instead of the BinaryFormatter in the above code,    //And call Serialize and Deserialize as before.  This formatter generates the following output for the example used above.  }
}

I hope this article will be helpful to everyone's C# programming.