C#常见序列化与反序列化操作

本案例主要实现以下几种方式的序列化与反序列化操作,可以通过设置SerializeType 参数进行切换

  1. JSON
  2. XML
  3. 二进制文件
using Newtonsoft.Json;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace IntelligentAssemblySystem.Helpers
{
    public static class SerializeHelper
    {
        /// <summary>
        /// 将对象序列化为指定文件
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="path"></param>
        /// <param name="type"></param>
        public static void Serialize(this object instance, string path, SerializeType type = SerializeType.Json)
        {
            // 先将文件进行备份后再进行存储
            if (File.Exists(path))
            {
                string directoryName = Path.GetDirectoryName(path);
                string fileName = Path.GetFileNameWithoutExtension(path);
                string extension = Path.GetExtension(path);
                string backupDirectory = $"{directoryName}/backup/{fileName}/";
                if (!Directory.Exists(backupDirectory)) Directory.CreateDirectory(backupDirectory);
                string backupFileName = $"{backupDirectory}/{fileName}_{DateTime.Now:yyyy_MM_dd_HH_mm_ss}{extension}";

                File.Copy(path, backupFileName, true);
            }
            else
            {
                // 若路径不存在,先检查文件夹是否存在,不存在则创建文件夹,再创建文件
                string directoryName = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
                    Directory.CreateDirectory(directoryName);

                File.Create(path).Close();
            }

            switch (type)
            {
                case SerializeType.Json:
                    {
                        File.WriteAllText(path, JsonConvert.SerializeObject(instance, Newtonsoft.Json.Formatting.Indented,
                            new JsonSerializerSettings
                            {
                                TypeNameHandling = TypeNameHandling.All
                            }));
                        break;
                    }
                case SerializeType.Xml:
                    {
                        using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                        {
                            if (instance == null) throw new ArgumentNullException(@"instance");

                            XmlSerializer serializer = new XmlSerializer(instance.GetType());
                            XmlWriterSettings settings = new XmlWriterSettings
                            {
                                Indent = true,
                                NewLineChars = "\r\n",
                                Encoding = Encoding.UTF8,
                                IndentChars = "    "
                            };

                            using (XmlWriter writer = XmlWriter.Create(stream, settings))
                            {
                                serializer.Serialize(writer, instance);
                            }
                        }
                        break;
                    }
                case SerializeType.Binary:
                    {
                        FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write,
                            FileShare.ReadWrite);
                        BinaryFormatter formatter = new BinaryFormatter();
                        try
                        {
                            formatter.Serialize(fs, instance);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            throw;
                        }
                        finally
                        {
                            fs.Close();
                        }

                        break;
                    }
                default:
                    throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }

        /// <summary>
        /// 将文件反序列化为指定对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string path, SerializeType type = SerializeType.Json)
        {
            T t = default(T);
            switch (type)
            {
                case SerializeType.Json:
                    {
                        t = JsonConvert.DeserializeObject<T>(File.ReadAllText(path), new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.All
                        });
                        break;
                    }
                case SerializeType.Xml:
                    {
                        var serializer = new XmlSerializer(typeof(T));
                        using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            using (var reader = XmlReader.Create(fs))
                            {
                                t = (T)serializer.Deserialize(reader);
                            }
                        }

                        break;
                    }
                case SerializeType.Binary:
                    {
                        FileStream fs = new FileStream(path, FileMode.Open);
                        BinaryFormatter formatter = new BinaryFormatter();
                        try
                        {
                            t = (T)formatter.Deserialize(fs);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            throw;
                        }
                        finally
                        {
                            fs.Close();
                        }

                        break;
                    }
                default:
                    throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            return t;
        }
    }

    public enum SerializeType
    {
        /// <summary>
        /// JSON格式
        /// </summary>
        Json,

        /// <summary>
        /// XML格式
        /// </summary>
        Xml,

        /// <summary>
        /// 二进制格式
        /// </summary>
        Binary
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值