且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

二进制BinaryFormatter 泛型 序列化与反序列化 (保存文件到本地和读取)

更新时间:2021-07-30 03:51:08

搬迁原来博客海澜CSDN

#region using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
#endregion

public class SerializeOrDeserializeFile
{
    /// <summary>
    /// 序列化指定数据结构
    /// </summary>
    /// <typeparam name="T">指定的数据结构类型</typeparam>
    /// <param name="tempSerializeList">指定数据结构实例</param>
    /// <param name="absolutePath">绝对路径</param>
    public static void SerializeMethod<T>(T tempSerializeList,string absolutePath)   // 二进制序列化    
    {
        //检测指定文件和其文件夹是否存在
        FileInfo tempFileInfo = new FileInfo(absolutePath);       
        if (!tempFileInfo.Exists)
        {
            string parentDirectory = tempFileInfo.DirectoryName;
            if (!Directory.Exists(parentDirectory))
            {
                Directory.CreateDirectory(parentDirectory);
            }
        }
        //序列化
        FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate);
        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, tempSerializeList);
            fs.Close();
        }
        catch (Exception ex)
        {
            fs.Close();
            Debug.Log($"序列异常信息:{ex}");
        }
    }
    /// <summary>
    /// 反序列化指定数据结构
    /// </summary>
    /// <typeparam name="T">指定的数据结构实例</typeparam>
    /// <param name="absolutePath">文件绝对类型</param>
    /// <returns></returns>
    public static T DeserializeMethod<T>(string absolutePath)   // 二进制反序列化    
    {
        T tempDeserialize;
        FileInfo binaryFile = new FileInfo(absolutePath);
        if (!binaryFile.Exists)
        {
            Debug.Log("反序列化文件不存在");
            return default(T);
        }
        FileStream fs = new FileStream(absolutePath, FileMode.OpenOrCreate);
        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            tempDeserialize = (T)bf.Deserialize(fs);
            fs.Close();
            return tempDeserialize;
        }
        catch (Exception ex)
        {
            Debug.LogWarning(ex);
            fs.Close();
            Debug.Log($"反序列异常信息:{ex}");
            return default(T);
        }
    }
}