using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace BPASmartClient.Helper { public class DataRecord { /// /// 读取序列化文件 /// /// 需要读取序列化文件的文件名,包括后缀名 /// 返回序列化读取到的信息,需要自行转换成对应的类型 public ReadT Read(string FilePath) { if (File.Exists(FilePath)) { FileStream fs = new FileStream(FilePath, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); var res = (ReadT)bf.Deserialize(fs); fs.Close(); return res; } return default; } public object Read(string filepath) { if (File.Exists(filepath)) { FileStream fs = new FileStream(filepath, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); var res = bf.Deserialize(fs); fs.Close(); return res; } return default; } /// /// 保存序列化文件 /// /// 需要通过序列化保存的对象 /// 设置保存的文件名,包括后缀名,后缀名可以自定义 public void Save(SaveT obj, string FileName) { Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"AccessFile\\ProductionData")); string path = $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\ProductionData\\{FileName}"; if (obj != null) { FileStream fs = new FileStream(path, FileMode.Create); BinaryFormatter bf = new BinaryFormatter();//创建一个二进制格式化器 bf?.Serialize(fs, obj); fs.Close(); } } } }