zoukankan      html  css  js  c++  java
  • 将对象xml序列化和反序列化

    //将一个对象按XML序列化的方式写入到一个文件,使用的默认的UTF8编码格式

    //o为要序列化的对象

    //path保存文件的路径

    public static object  _lockObj=new object();

    public static void XmlSerializeToFile(object o,string path)

    {

       XmlSerializeToFile(o,path,Encoding.UTF8);

    }

    //encoding 编码方式

    //path 文件路径

    public static void XmlSerializeToFile(object o,string path,Encoding encoding)

    {

      if(string.IsNullOrEmpty(path))

        throw new ArgumentNullException("path");

      Monitor.Enter(_lockObj);//添加排他锁,解决并发写入问题

      try

      {

         using(FileStream file=new FileStream(path,FileMode.Create,FileAccess.Write))

         {

             XmlSerializeInternal(file,o,encoding);

         }

      }

      catch(Exception)

      {

         throw;

      }

      finally

      {

         Monitor.Exit(_lockObj);

      }

    }

    //读入一个文件,并按XML的方式反序列化对象

    public static T XmlDeserializeFromFile<T>(string path,Encoding encoding)

    {

      if(string.IsNullOrEmpty(path))

      throw new ArgumentNullException("path");

      if(encoding == null)

      throw new ArgumentNullException("encoding");

      string xml=File.ReadAllText(path,encoding);

      return XmlDeserialize<T>(xml,encoding);

    }

    pubic static T XmlDeserializeFromFile<T>(string path)

    {

      return XmlDeserializeFromFile<T>(path,Encoding.UTF8);

    }

  • 相关阅读:
    P1031 均分纸牌
    P1130 红牌
    P1094 纪念品分组
    win32 公用对话框
    高性能完成端口socket服务(IOCP)
    一个简单的调试日志功能
    UI设计工具
    windows平台(不包括ARM的CE)通用的压缩和解压缩
    win api 实现 AES加密、解密,获取HASH
    win32sdk 编程整理的些资料
  • 原文地址:https://www.cnblogs.com/huodige/p/10654872.html
Copyright © 2011-2022 走看看