C#持久化对象为XML文件(MyXmlSerializer)
作者:C/S框架网|www.cscode.ne  发布日期:2020-04-30 20:05:49
  C#持久化对象为XML文件(MyXmlSerializer)

C#持久化对象为XML文件(MyXmlSerializer)


C# Code:

/// <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);
    }
    
  }
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



序列化对象到XML文件:


C# Code:

string versionFile = Application.StartupPath + XML_FILE;
MyXmlSerializer.Serialize(
this, versionFile);

//来源:C/S框架网 | www.csframework.com | QQ:23404761



从XML文件反序列化为对象:


C# Code:

object o = MyXmlSerializer.Deserialize(typeof(VersionHistory), versionFile);

//来源:C/S框架网 | www.csframework.com | QQ:23404761





C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务

上一篇 下一篇