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

搬迁原来博客海澜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
{
    /// 
    /// 序列化指定数据结构
    /// 
    /// 指定的数据结构类型
    /// 指定数据结构实例
    /// 绝对路径
    public static void SerializeMethod(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}");
        }
    }
    /// 
    /// 反序列化指定数据结构
    /// 
    /// 指定的数据结构实例
    /// 文件绝对类型
    /// 
    public static T DeserializeMethod(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);
        }
    }
}

你可能感兴趣的:(二进制BinaryFormatter 泛型 序列化与反序列化 (保存文件到本地和读取))