zoukankan      html  css  js  c++  java
  • C#Object与XML文件或二进制文件之间的转化

    Object To Xml 文件

     public static bool Serializer<T>(object obj, string path)
          {
              FileStream xmlfile = new FileStream(path, FileMode.OpenOrCreate);
              
              //创建序列化对象 
              XmlSerializer xml = new XmlSerializer(typeof(T));
              try
              {    //序列化对象
                  xml.Serialize(xmlfile, obj);
                  xmlfile.Close();
              }
              catch (InvalidOperationException)
              {
                  throw;
              }
              
              return true;
              
          }

    Xml To Object

     public static T Deserializer<T>(string path)
          {
              try
              {
                  FileStream xmlfile = new FileStream(path, FileMode.Open);
    
                  XmlSerializer xml = new XmlSerializer(typeof(T));
                  //序列化对象
                  //xmlfile.Close();
                  T t = (T)xml.Deserialize(xmlfile);
                  xmlfile.Close();
                  return t;
              }
              catch (InvalidOperationException)
              {
                  throw;
              }
              catch (FileNotFoundException)
              { throw; }
              finally
              {
                  
              }
          }
    

      

    Object To Bin

    public static bool BinarySerializer(object obj, string path)
          {
              FileStream Stream = new FileStream(path, FileMode.OpenOrCreate);
              //创建序列化对象 
              BinaryFormatter bin = new BinaryFormatter();
              try
              {    //序列化对象
                  bin.Serialize(Stream, obj);
                  Stream.Close();
              }
              catch (InvalidOperationException)
              {
                  throw;
              }
              return true;
          }
    

      

    Bin To Object

    public static T BinaryDeserializer<T>(string path)
          {
              try
              {
                  FileStream binfile = new FileStream(path, FileMode.Open);
    
                  BinaryFormatter bin = new BinaryFormatter();
                  //序列化对象
                  //xmlfile.Close();
                  T t = (T)bin.Deserialize(binfile);
                  binfile.Close();
                  return t;
              }
              catch (InvalidOperationException)
              {
                  throw;
              }
              catch (FileNotFoundException)
              { throw; }
              finally
              {
    
              }
          }
    

      

  • 相关阅读:
    ▶ 0001 No application 'E:wwwgolog' found in your GOPATH
    beego路由
    go sync.WaitGroup
    idea修改filetype
    deepin添加设置快捷键
    mysql数据库被攻击
    linux桌面系统的约定
    deepin把vscode设为默认文本应用
    linux应用管理
    当你在工作中失去动力时该怎么办?
  • 原文地址:https://www.cnblogs.com/jesszhu/p/3276556.html
Copyright © 2011-2022 走看看