c# serialization application

Posted by AliasBDI on Mon, 10 Jan 2022 07:28:48 +0100

The article is reproduced in https://kb.cnblogs.com/page/78824/

Serialization is the process of storing the state of an object instance to a storage medium. In this process, first convert the public and private fields of the object and the name of the class (including the assembly where the class is located) into a byte stream, and then write the byte stream to the data stream. When the object is subsequently deserialized, an exact copy of the original object is created.

We often need to save the field value of the object to disk and retrieve this data later. Although you can do this without serialization, this approach is often cumbersome and error prone, and becomes more and more complex when you need to track the hierarchy of objects. Imagine writing a large business application with a large number of objects. Programmers have to write code for each object in order to save fields and attributes to and restore them from disk. Serialization provides a quick and easy way to achieve this goal.

     . NET common language runtime (CLR) manages the distribution of objects in memory NET framework provides automatic serialization mechanism by using reflection. After the object is serialized, the name of the class, the assembly, and all data members of the class instance are written to the storage media. Objects usually use member variables to store references to other instances. After class serialization, the serialization engine will track all serialized reference objects to ensure that the same object is not serialized multiple times The serialization architecture provided by. NET framework can automatically and correctly handle object diagrams and circular references. The only requirement for object diagrams is that all objects referenced by the object being serialized must be marked Serializable (see basic serialization). Otherwise, an exception occurs when the serializer attempts to serialize an unmarked object.

When a serialized class is deserialized, the class is recreated and the values of all data members are automatically restored.

There are three common serialization methods in C#: BinaryFormatter, SoapFormatter and XML serialization. This paper mainly talks about the specific use and similarities and differences of these three methods through a small example.

Create a new vs2008 console project SerializableTest, add a Person class, and add [Serializable] to make it Serializable

?
123456789101112131415161718192021222324using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace SerializableTest{    [Serializable]    public class Person    {        public string Sno { get; set; }        public string Name { get; set; }        public string Sex { get; set; }        public int Age { get; set; }         public string DisplayInfo()        {             return "My student number is:" +Sno+ "\n My name is:"+Name + "\n My gender is:"+Sex+"\n My age:"+Age+"\n";                 }     }}

1, BinaryFormatter serialization mode

1. Serialization: create a new Person object me, and then save its serialization to the file personinfo Txt]

?
1234567891011121314var me = new Person                         {                             Sno = "200719",                             Name = "yuananyun",                             Sex="man",                             Age=22                          };            //Create an instance of formatter {IFormatter formatter = new BinaryFormatter(); / / create a file stream {Stream stream = new FileStream("c:/personInfo.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);             formatter.Serialize(stream, me);             stream.Close();

Executing the above code will create a personinfo Txt file, which contains the assembly information, class name and field information of the me object.

2. Deserialization: from the file personinfo Txt to restore an object

?
12345//Deserialization: Stream destream = new FileStream("c:/personInfo.txt", FileMode.Open, FileAccess.Read, FileShare.Read);            var stillme = (Person)formatter.Deserialize(destream);            stream.Close();

The whole procedure is as follows:

?
12345678910111213141516171819202122232425262728293031323334353637383940414243using System;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary; namespace SerializableTest{    class Program    {        static void Main(string[] args)        {            //Create an instance of formatter {IFormatter formatter = new BinaryFormatter();             Console.WriteLine("object serialization start...");             var me = new Person                         {                             Sno = "200719",                             Name = "yuananyun",                             Sex="man" ,                             Age=22                          }; / / create a file stream {Stream stream = new FileStream("c:/personInfo.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);             formatter.Serialize(stream, me);             stream.Close();             Console.WriteLine("end of serialization! \ n");             Console.WriteLine("deserialization start..."); / / deserialize Stream destream = new FileStream("c:/personInfo.txt", FileMode.Open, FileAccess.Read, FileShare.Read);             var stillme = (Person)formatter.Deserialize(destream);             stream.Close();             Console.WriteLine("end of deserialization, output object information...");             Console.WriteLine(stillme.DisplayInfo());             Console.ReadKey();           }    }}

The operation results are as follows:

Note: when deserializing a restored object, the constructor of the Person class is not called

2, SoapFormatter serialization mode

Similar to BinaryFormatter serialization, you only need to change IFormatter formatter = new BinaryFormatter() to IFormatter formatter = new SoapFormatter(), and reference assembly system Runtime. Serialization. Formatters. Soap. DLL (. net comes with)

?
12345678910111213141516171819202122232425262728293031323334353637383940414243using System;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Soap; namespace SerializableTest{    class Program    {        static void Main(string[] args)        {            //Create an instance of formatter {IFormatter formatter = new SoapFormatter();             Console.WriteLine("object serialization start...");             var me = new Person                         {                             Sno = "200719",                             Name = "yuananyun",                             Sex="man" ,                             Age=22                          }; / / create a file stream {Stream stream = new FileStream("c:/personInfo.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);             formatter.Serialize(stream, me);             stream.Close();             Console.WriteLine("end of serialization! \ n");             Console.WriteLine("deserialization start..."); / / deserialize Stream destream = new FileStream("c:/personInfo.txt", FileMode.Open, FileAccess.Read, FileShare.Read);             var stillme = (Person)formatter.Deserialize(destream);             stream.Close();             Console.WriteLine("end of deserialization, output object information...");             Console.WriteLine(stillme.DisplayInfo());             Console.ReadKey();           }    }}

The result is the same as the first method.

The serialized file is a file in SOAP format (Simple Object Access Protocol (SOAP). It is a lightweight, simple and XML based protocol. It is designed to exchange structured and solidified information on the WEB. SOAP can be combined with many existing Internet protocols and formats, including Hypertext Transfer Protocol (HTTP), simple mail transfer protocol (SMTP), and Multipurpose Internet mail extension protocol (MIME). It also supports a wide range of applications from messaging systems to remote procedure calls (RPC s). SOAP uses a combination of XML based data structures and Hypertext Transfer Protocol (HTTP) to define a standard way to use distributed objects in various operating environments on the Internet, The contents are as follows:

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/SerializableTest/SerializableTest%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<_x003C_Sno_x003E_k__BackingField id="ref-3">200719</_x003C_Sno_x003E_k__BackingField>
<_x003C_Name_x003E_k__BackingField id="ref-4">yuananyun</_x003C_Name_x003E_k__BackingField>
<_x003C_Sex_x003E_k__BackingField id="ref-5">man</_x003C_Sex_x003E_k__BackingField>
<_x003C_Age_x003E_k__BackingField>22</_x003C_Age_x003E_k__BackingField>
</a1:Person>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

3, XML serialization mode

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445using System;using System.IO;using System.Runtime.Serialization;using System.Xml.Serialization;  namespace SerializableTest{    class Program    {        static void Main(string[] args)        {            //Create an instance of the formatter {XmlSerializer formatter = new XmlSerializer(typeof(Person));              Console.WriteLine("object serialization start...");             var me = new Person                         {                             Sno = "200719",                             Name = "yuananyun",                             Sex="man" ,                             Age=22                          }; / / create a file stream {Stream stream = new FileStream("c:/personInfo.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);             formatter.Serialize(stream, me);             stream.Close();             Console.WriteLine("end of serialization! \ n");             Console.WriteLine("deserialization start..."); / / deserialize Stream destream = new FileStream("c:/personInfo.txt", FileMode.Open, FileAccess.Read, FileShare.Read);             var stillme = (Person)formatter.Deserialize(destream);             stream.Close();             Console.WriteLine("end of deserialization, output object information...");             Console.WriteLine(stillme.DisplayInfo());             Console.ReadKey();           }    }}

The result is the same as the above. The file after xml serialization is a general xml file, personinfo Txt reads as follows:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Sno>200719</Sno>
  <Name>yuananyun</Name>
  <Sex>man</Sex>
  <Age>22</Age>
</Person>

Note: xml serialization can only save public fields and read-write attributes, and private fields cannot be serialized

Verify below

Change the Name attribute of Person to Private, and then view the generated personinfo Text, which reads as follows:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Sno>200719</Sno>
  <Sex>man</Sex>
  <Age>22</Age>
</Person>

You can see that the Name attribute does not appear in the file, and the value of the Name attribute in the object generated by deserialization is NULL.

The above three methods of c# serialization and deserialization are illustrated. Of course, you can also decide whether to serialize or not those attributes in a class. You can prevent them from being serialized by marking member variables with the NonSerialized attribute