【C#进阶八】C#中的序列化与反序列化下(二进制序列化、XML序列化及JSON序列化)

【C#进阶八】C#中的序列化与反序列化下(二进制序列化、XML序列化及JSON序列化)_第1张图片

文章目录

    • 二进制序列化与反序列化
      • 序列化与反序列化代码示例
      • 运行结果

上一篇介绍了XML序列化及JSON序列化,这一篇接着介绍二进制序列化。
【C#进阶七】C#中的序列化与反序列化上(二进制序列化、XML序列化及JSON序列化)

二进制序列化与反序列化

可以将序列化定义为一个将对象状态存储到存储介质的过程。 在这个过程中,对象的公共字段和私有字段以及类(包括含有该类的程序集)的名称,将转换成字节流,而字节流接着将写入数据流。 随后对该对象进行反序列化时,将创建原始对象的准确克隆。二进制序列化允许修改对象内部的私有成员,从而更改其状态。

序列化与反序列化代码示例

Main文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using objTtext;

namespace ConsoleApp1
{
    internal class Class2
    {
        /// 
        /// 将对象写入文件,然后再读取文件(序列化与反序列化)
        /// 
        static void Main()
        {
            //序列化
            RecordDetail recordDetail = new RecordDetail();
            recordDetail._opendatetime = DateTime.Now.ToString();
            recordDetail._userOpenType = "密码";
            recordDetail._userSettingType = "管理员";
            userDetails userDetails = new userDetails();
            var thTH = new System.Globalization.CultureInfo("th-TH");
            DateTime dat = new DateTime(2099, 5, 28, thTH.DateTimeFormat.Calendar);
            userDetails._aollowTime = dat.ToString();
            recordDetail.userDetails = userDetails;
            recordDetail._settingdatetime = DateTime.Now.ToString();
            WarningRecordDetails warningRecordDetails = new WarningRecordDetails();
            warningRecordDetails._warningStatus = "true";
            warningRecordDetails._warningdatetime = DateTime.Now.ToString();
            //反序列化
            Console.WriteLine("将对象写入文件".PadLeft(50, '-'));
            practice03.WriteData(recordDetail, warningRecordDetails, "record");
            Console.WriteLine("从文件中读取对象的数据".PadLeft(50, '-'));
            RecordGolable recordGolable =  new ConsoleApp1.RecordGolable();
            recordGolable = practice03.ReadDataToMemory("record");
            int i = 0;
            foreach (RecordDetail recorddetail in recordGolable._recordDetailList)
            {
                i++;
                Console.WriteLine($"第{i}个");
                Console.WriteLine( recorddetail._opendatetime);               
                Console.WriteLine( recorddetail._settingdatetime.ToString());               
                Console.WriteLine( recorddetail.userDetails._aollowTime);
                Console.WriteLine( recorddetail._userOpenType);
                Console.WriteLine( recorddetail._userSettingType);
            } 
        }
    }
}

类文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    /// 
    /// 用户操作记录类
    /// 
    [Serializable]
    internal class RecordDetail
    {
        /// 
        /// 用户开锁时间
        /// 
        public string _opendatetime { set; get; } = string.Empty;
        /// 
        /// 用户设置时间
        /// 
        public string _settingdatetime { get; set; } = string.Empty;
        /// 
        /// 用户信息类实例化
        /// 
        public userDetails userDetails = new userDetails();
        /// 
        /// 开锁的方式
        /// 
        public string _userOpenType { get; set; } = string.Empty;
        /// 
        /// 用户设置类型
        /// 
        public string _userSettingType { get; set; } = string.Empty;
        /// 
        /// 用户设置的细节
        /// 
        public string _userSettingDetails { get; set; } = string.Empty;
    }

    [Serializable]
    internal class userDetails
    {
        /// 
        /// 用户Id
        /// 
        public string _useId { get; set; } = string.Empty;
        /// 
        /// 用户姓名
        /// 
        public string _useName { get; set; } = string.Empty;
        /// 
        /// 用户职位
        /// 
        public string _userjob { get; set; } = string.Empty;
        /// 
        /// 用户权限级别
        /// 
        public int _uselevel { get; set; } = 0;
        /// 
        /// 用户授权时间
        /// 
        public string _aollowTime { get; set; } = string.Empty;
    }

    /// 
    /// 报警操作记录类
    /// 
    [Serializable]
    internal class WarningRecordDetails
    {
        /// 
        /// 报警的时间
        /// 
        public string _warningdatetime { get; set; } = string.Empty;
        /// 
        /// 报警的类型
        /// 
        public string _warningType { get; set; } = string.Empty;
        /// 
        /// 报警的状态
        /// 
        public string _warningStatus { get; set; } = string.Empty;
    }

    /// 
    /// 全局集合类
    /// 
    [Serializable]
    internal class RecordGolable
    {
        /// 
        /// 用户集合
        /// 
        public List _recordDetailList = new List();
        /// 
        /// 报警集合
        /// 
        public List _warningRecordList = new List();
        /// 
        /// 用户信息字段,全局变量,方便查询
        /// 
        public Dictionary> _dicRecordDetail = new Dictionary>();
        /// 
        /// 抱紧信息字典,全局变量,方便查询
        /// 
        public Dictionary> _dicWarningRecord = new Dictionary>();
    }


}

序列化与反序列化方法

using ConsoleApp1;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace objTtext
{
    class practice03
    {
        /// 
        /// 往文件中写数据
        /// 
        /// 
        /// 
        /// 
        public static void WriteData(RecordDetail recordDetail, WarningRecordDetails warningRecord, string wrType = "")
        {
                try
                {
                    //创建文件夹
                   byte[] pReadByte = new byte[3000];
                    string dataDir = @"G:\Desktop\archive1" + "\\Records";
                    if (!Directory.Exists(dataDir))// 目录不存在,新建目录
                    {
                        Directory.CreateDirectory(dataDir);
                    }
                    if (wrType == "record")
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            IFormatter bf = new BinaryFormatter();
                            bf.Serialize(ms, recordDetail);
                            pReadByte = ms.GetBuffer();
                        }
                    }
                    else if (wrType == "warning")
                    {
                        //byte[] pReadByte;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            IFormatter bf = new BinaryFormatter();
                            bf.Serialize(ms, warningRecord);
                            pReadByte = ms.GetBuffer();
                        }
                    }
                    else
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  记录信息保存有误!", "错误!");
                        return;
                    }
                    //将二进制写入文件
                    string str = string.Empty;
                    for (int i = 0; i < pReadByte.Length; i++)
                    {
                        str += pReadByte[i].ToString("X2");
                    }
                    String userfile =Path.Join(dataDir,"\\text.data");
                    FileStream fs = new FileStream(userfile, FileMode.OpenOrCreate, FileAccess.ReadWrite,  FileShare.ReadWrite);
                    fs.Seek(0, System.IO.SeekOrigin.End); //跳到流尾追加
                    //文件节流点
                    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                    sw.WriteLine(str);//二进制写入文件
                    sw.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception" + ex.Message);
                    return;
                }              
        }
        /// 
        /// 从文件中读取对象到内存
        /// 
        /// 
        /// 
        public static RecordGolable ReadDataToMemory(string readtype = "")
        {
            RecordGolable recordGolable = new RecordGolable();
            RecordDetail recordDetail = new RecordDetail();
            BinaryFormatter bf = new BinaryFormatter();
            try
            {
                if (readtype == "record")
                {
                    //获取用户记录信息到内存字典中
                    string dataDir = @"G:\Desktop\archive1" + "\\Records";
                    String userfile = Path.Join(dataDir, "\\text.data");
                    FileStream fs = new FileStream(userfile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    StreamReader read = new StreamReader(fs);
                    //循环读取每一行
                    string strReadline = string.Empty;
                    while ((strReadline = read.ReadLine()) != null)
                    {
                        //对每一行数据做反序列化处理
                        if (strReadline.Length % 2 != 0)
                        {
                            strReadline = "0" + strReadline;
                        }
                        byte[] binReadline = new byte[strReadline.Length / 2];
                        for (int i = 0; i < binReadline.Length; i++)
                        {
                            string b = strReadline.Substring(i * 2, 2);
                            binReadline[i] = Convert.ToByte(b, 16);
                        }
                        using (MemoryStream ms = new MemoryStream(binReadline))
                        {
                            IFormatter iFormatter = new BinaryFormatter();
                            recordDetail = (RecordDetail)iFormatter.Deserialize(ms);
                        }
                        recordGolable._recordDetailList.Add(recordDetail);
                    }
                }
                else if (readtype == "warning")
                {
                    //获取用户记录信息到内存字典中
                    string dataDir = Environment.CurrentDirectory + "Records";
                    FileStream fs = new FileStream(dataDir, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    StreamReader read = new StreamReader(fs);
                    //循环读取每一行
                    string strReadline = string.Empty;
                    while ((strReadline = read.ReadLine()) != null)
                    {
                        //对每一行数据做反序列化处理
                        if (strReadline.Length % 2 != 0)
                        {
                            strReadline = "0" + strReadline;
                        }
                        byte[] binReadline = new byte[strReadline.Length / 2];
                        for (int i = 0; i < binReadline.Length; i++)
                        {
                            string b = strReadline.Substring(i * 2, 2);
                            binReadline[i] = Convert.ToByte(b, 16);
                        }
                        using (MemoryStream ms = new MemoryStream(binReadline))
                        {
                            IFormatter iFormatter = new BinaryFormatter();
                            recordDetail = (RecordDetail)iFormatter.Deserialize(ms);
                        }
                        recordGolable._recordDetailList.Add(recordDetail);
                    }
                }
                recordGolable._dicRecordDetail = new Dictionary>();
                recordGolable._dicRecordDetail.Add(recordDetail.userDetails._useId, recordGolable._recordDetailList);
                return recordGolable;
            }
            catch (Exception ex)
            {
                Console.WriteLine( "Write RecordData Exception: " + ex.Message);
                return recordGolable;
            } 
        }
    }
}

运行结果

部分截图

【C#进阶八】C#中的序列化与反序列化下(二进制序列化、XML序列化及JSON序列化)_第2张图片

保存的二进制文件

【C#进阶八】C#中的序列化与反序列化下(二进制序列化、XML序列化及JSON序列化)_第3张图片
参考资料:
https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/
欢迎关注公众号【智能建造小硕】(分享计算机编程、人工智能、智能建造、日常学习和科研经验等,欢迎大家关注交流。)

你可能感兴趣的:(C#进阶笔记,c#,xml,json)