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
          {

          }
      }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM