C serialization and deserialization instances

  • 2020-12-16 06:04:24
  • OfStack

This article shows an example of how C# serializes and deserializes. Share to everybody for everybody reference. The specific analysis is as follows:

The process of converting an object into a sequence of bytes is called object serialization. The process of restoring a "sequence of bytes" to an "object" is called object deserialization.
serialization

using System;  
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Runtime.Serialization.Formatters.Binary; 
 
namespace Serialization and deserialization  

    // Serialization is the process of converting an object to 2 Into the system  
    // To deserialize is to take 2 Convert base to object  
 
    // Serialization and deserialization are used to transfer data.   
    // When we transmit data over the network, we only have 2 The base form can be transmitted. So whatever we transmit over the network, we serialize what you want to transmit first to 2 Base data, the other side receives the same 1 a 2 Base data, it needs to do this again 2 The base data is deserialized into 1 An object.  
 
    // We want to serialize 1 A class, the first 1 The step is to mark the class as serializable. with [Serializable] The keyword. Only by [Serializable] The object created by the tagged class can be serialized  
 
    [Serializable] // this [Serializable] The function is: indication 1 Five classes can be serialized. This class cannot be inherited.  
    public class Person 
    { 
        public string Name { get; set; } 
 
        public int Age{get;set;} 
 
        public char Gender{get;set;} 
 
        public Person() { } 
 
        public Person(string name, int age, char gender) 
        { 
            this.Name = name; 
            this.Age = age; 
            this.Gender = gender; 
        } 
    } 
 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            // Now we're going to take p This object is transmitted to the other person's computer. Now there is no other party's computer, so I will simulate on my own computer 1 Bottom: Pass now 1 A flow will p This object is converted to 2 Base, write it on my desktop. And then we're going to take this 2 Base files are deserialized into 1 An object  
            Person p = new Person(" Xue hui ", 25, ' female '); 
            using (FileStream stream = new FileStream(@"C:\Users\ Every bin \Desktop\11.txt", System.IO.FileMode.OpenOrCreate, FileAccess.Write)) 
            {  
                // Start serializing objects. You need to start serializing objects 1 A class  
                BinaryFormatter bf = new BinaryFormatter(); 
 
                //public void Serialize(Stream serializationStream, object graph); this Serialize Methods the first 1 Is the stream file into which the object is to be serialized 2 The parameter is the object to serialize  
                bf.Serialize(stream, p); 
            } 
            Console.WriteLine(" Serialization complete "); 
        } 
    } 
}

deserialization

using System;  
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Runtime.Serialization.Formatters.Binary; 
 
namespace Serialization and deserialization  

    [Serializable] 
    public class Person 
    { 
        public string Name { get; set; } 
 
        public int Age { get; set; } 
 
        public char Gender { get; set; } 
    } 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            // Now let's go back to what we just wrote on the desktop 2 Base stream file 11.txt By deserializing to 1 An object
            using (FileStream stream2 = new FileStream(@"C:\Users\ Every bin \Desktop\11.txt", FileMode.Open, FileAccess.Read)) 
            { 
                BinaryFormatter bf2 = new BinaryFormatter(); 
 
                //public object Deserialize(Stream serializationStream); this Deserialize The argument to the method is: to deserialize 2 Base stream file. Its return value is 1 a object So we're going to take this object Equivalent to Person Type.  
                Person p2=(Person) bf2.Deserialize(stream2); 
 
                Console.WriteLine(" Side serialization successful "); 
                Console.WriteLine(p2.Name); // Output: Xue Hui  
                Console.ReadKey(); 
            } 
        } 
    } 
}

serialization

Serialize 1 instance of this class to 1 file:
MyFile. bin is a file that serializes obj objects into persistent storage.

MyObject obj = new MyObject();   
obj.n1 = 1;  
obj.n2 = 24;  
obj.str = "1 Some of the string ";  
IFormatter formatter = new BinaryFormatter();  
Stream MyStream = new FileStream("MyFile.bin", FileMode.Create,  
FileAccess.Write, FileShare.None);  
formatter.Serialize(MyStream, obj);  
stream.Close();

deserialization

This is a deserialization of 1 MyFile. bin file into 1 obj object
[filestream reads the file stream and deserializes it into an object using the.net serializer]

IFormatter formatter = new BinaryFormatter();   
Stream MyStream = new FileStream("MyFile.bin", FileMode.Open,  
FileAccess.Read, FileShare.Read);  
MyObject obj = (MyObject) formatter.Deserialize(MyStream);  
stream.Close();

xml

Serialize an instance of this class into an Xml file

XmlSerializer ser = new XmlSerializer(obj.GetType());    
ser.Serialize(new FileStream(@"users.xml", FileMode.Create), obj);

deserialization

XmlSerializer serializer = new XmlSerializer(Type.GetType("MyObject"));
MyObject my=(MyObject)serializer.Deserialize(new FileStream(@"users.xml",FileMode.Open));

Serialization DataTable

The main purpose is to enable the next time to start the project to read the last saved object information. In layman's terms, you save an object and restore it at a particular time. There are also three common serialization methods in C# : BinaryFormatter, SoapFormatter, and XML serialization. Today's focus is on the XML serialization, which is saved for the content serialization of DataTable.

/// <summary>  
/// DataTable serialization  
/// </summary> 
/// <param name="dt"> Serialized DataTable</param> 
/// <param name="path"> The path </param> 
public void Serializer(DataTable dt,string path) 

    XmlSerializer serializer = new XmlSerializer(typeof(System.Data.DataTable)); 
    System.Xml.XmlWriter writer= System.Xml.XmlWriter.Create(path); 
    serializer.Serialize(writer, dt); 

 
// deserialization  
private void InitData(string filePath) 

    XmlSerializer serializer = new XmlSerializer(typeof(System.Data.DataTable)); 
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None); 
    DataTable dt = (DataTable)serializer.Deserialize(fs); 
    for (int i = 0; i < dt.Rows.Count; i++) 
    { 
        int j = dgvDeviceInfo.Rows.Add(); 
        dgvDeviceInfo.Rows[j].SetValues(dt.Rows[i][" equipment ID"].ToString(), 
            dt.Rows[i][" The serial number "].ToString(), 
            dt.Rows[i][" Device name "].ToString(), 
            dt.Rows[i][" Serial number "].ToString(), 
            dt.Rows[i][" The connection information "].ToString(), 
            dt.Rows[i][" note "].ToString(), 
            dt.Rows[i]["TagID"].ToString()); 
    } 
}

Hopefully, this article has helped you with your C# programming.


Related articles: