自定义一个序列化类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; namespace PrintDatas.Functionlayer { class SerializableOperate { /// <summary> /// 序列化Font /// </summary> public static void ObjectSerializable(object obj, string filePath) { FileStream fs = null; try { if (!Directory.Exists(Top.Api.Sync.MsgDecode.Fontset)) { Directory.CreateDirectory(Top.Api.Sync.MsgDecode.Fontset); } fs = new FileStream(filePath, FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, obj); } catch { Console.WriteLine("序列化出错"); } finally { fs.Close(); } } /// <summary> /// 反序列化Font /// </summary> public static object ObjectUnSerializable(string filePath) { FileStream fs = null; object obj = null; try { fs = new FileStream(filePath, FileMode.OpenOrCreate); BinaryFormatter bf = new BinaryFormatter(); obj = bf.Deserialize(fs); } catch (Exception ex) { Console.WriteLine("反序列化出错:" + ex.Message); return null; } finally { fs.Close(); } return obj; } } }
调用序列化:
txtTishi.Font = fontDialog1.Font;
SerializableOperate.ObjectSerializable(fontDialog1.Font, MsgDecode.Fontset + MsgDecode.Fontset2 + txtTishi.Name);
调用反序列化
Font fon = (Font)SerializableOperate.ObjectUnSerializable(MsgDecode.Fontset + MsgDecode.Fontset2 + txtTishi.Name);