#region
|
|
using System;
|
using System.IO;
|
using System.Xml.Serialization;
|
|
#endregion
|
|
namespace CSFrameworkV5.Common
|
{
|
/// <summary>
|
/// 对象序列化
|
/// </summary>
|
public class ObjectSerializer
|
{
|
/// <summary>
|
/// 读取XML文件,反序列化为对象实例
|
/// </summary>
|
/// <param name="objectType">指定对象类型</param>
|
/// <param name="file">文件名</param>
|
/// <returns>对象实例</returns>
|
public static object Deserialize(Type objectType, string file)
|
{
|
object o = null;
|
Stream stream = null;
|
try
|
{
|
if (File.Exists(file))
|
{
|
var xs = new XmlSerializer(objectType);
|
stream = new FileStream(file, FileMode.Open,
|
FileAccess.Read, FileShare.ReadWrite);
|
o = xs.Deserialize(stream);
|
stream.Close();
|
stream = null;
|
}
|
|
return o;
|
}
|
catch
|
{
|
if (stream != null) stream.Close();
|
|
return o;
|
}
|
}
|
|
/// <summary>
|
/// 将对象写入XML文件
|
/// </summary>
|
/// <param name="o">对象实例</param>
|
/// <param name="file">文件名</param>
|
public static void SerializeObject(object o, string file)
|
{
|
Stream stream = null;
|
try
|
{
|
var xs = new XmlSerializer(o.GetType());
|
stream = new FileStream(file, FileMode.Create, FileAccess.Write,
|
FileShare.ReadWrite);
|
xs.Serialize(stream, o);
|
stream.Flush();
|
stream.Close();
|
stream = null;
|
}
|
catch
|
{
|
if (stream != null) stream.Close();
|
}
|
}
|
}
|
}
|