zoukankan      html  css  js  c++  java
  • C# 序列化和反序列化

    自定义一个序列化类

    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);
  • 相关阅读:
    MFC
    AC自动机
    KMP
    Power Transmission (Hard Edition)
    Floyd
    地杰斯特算法
    二叉树
    51nod 1002 数塔取数问题【dp】
    51nod1049 最大子段和【动态规划】
    poj2385
  • 原文地址:https://www.cnblogs.com/jcdd-4041/p/3401175.html
Copyright © 2011-2022 走看看