zoukankan      html  css  js  c++  java
  • C#.Net 持久化对象为XML文件

    </pre><pre code_snippet_id="613717" snippet_file_name="blog_20150307_1_5795040" name="code" class="csharp">
    /// <summary> 
    /// 持久化对象为XML文件 
    /// </summary> 
    public class MyXmlSerializer
    {
       
       /// <summary> 
       /// 序列化对象 
       /// </summary> 
       /// <param name="o">对象</param> 
       /// <param name="outFile">持久化对象文件</param> 
       /// <returns></returns> 
       public static bool Serialize(object o, string outFile)
       {
          using (StringWriter sw = new StringWriter())
          {
             XmlSerializer xz = new XmlSerializer(o.GetType());
             xz.Serialize(sw, o);
             File.WriteAllText(outFile, sw.ToString(), Encoding.UTF8);
          }
          
          return true;
       }
       
       /// <summary> 
       /// 反序列化为对象 
       /// </summary> 
       /// <param name="type">对象类型</param> 
       /// <param name="s">持久化对象文件</param> 
       /// <returns></returns> 
       public static object Deserialize(Type type, string file)
       {
          string content = File.ReadAllText(file);
          
          using (StringReader sr = new StringReader(content))
          {
             XmlSerializer xz = new XmlSerializer(type);
             return xz.Deserialize(sr);
          }
          
       }
    }

    使用方法:

    /// <summary> 
    /// 获取历史记录, 反序列化 
    /// </summary> 
    /// <returns></returns> 
    public static VersionHistory GetVersionHistory()
    {
       string versionFile = Application.StartupPath XML_FILE;
       if (File.Exists(versionFile))
       {
          object o = MyXmlSerializer.Deserialize(typeof(VersionHistory), versionFile);
          return o as VersionHistory;
       }
       else
       return new VersionHistory();
    }
    
    /// <summary> 
    /// 保存历史记录,序列化 
    /// </summary> 
    public void Save()
    {
       string versionFile = Application.StartupPath XML_FILE;
       MyXmlSerializer.Serialize(this, versionFile);
    }


  • 相关阅读:
    C#编程总结(三)线程同步 多线程
    配置 Spring.NET
    C# Redis
    WPF MvvmLight RelayCommand 绑定Command 的使用
    WCF编程系列(一)初识WCF
    C#/WPF程序开机自动启动
    C# 创建Windows Service(Windows服务)程序
    前端Js框架汇总
    列式存储和行式存储
    llvm-3.4.2 编译失败 解决方案
  • 原文地址:https://www.cnblogs.com/zhaoshujie/p/9594773.html
Copyright © 2011-2022 走看看