C#持久化对象为XML文件(MyXmlSerializer)
MyXmlSerializer 源码
C# 全选
/// <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 T Deserialize<T>(string file) where T : new()
{
Type type = typeof(T);
string content = File.ReadAllText(file);
using (StringReader sr = new StringReader(content))
{
XmlSerializer xz = new XmlSerializer(type);
var o = xz.Deserialize(sr);
return (T)o;
}
}
}
Serialize - 序列化对象到XML文件
C# 全选
/// <summary>
/// 保存配置
/// </summary>
public static void Save(UserConfig config = null)
{
if (config == null) config = _Current;
var file = Path.Combine(Application.StartupPath, "user_config.xml");
MyXmlSerializer.Serialize(config, file);
}
Deserialize - 从XML文件反序列化为对象
C# 全选
/// <summary>
/// 加载配置
/// </summary>
public static void Load()
{
var file = Path.Combine(Application.StartupPath, "user_config.xml");
if (File.Exists(file))
_Current = MyXmlSerializer.Deserialize<UserConfig>(file);
else
_Current = new UserConfig();
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网