xml序列化的公共方法
public enum SerializeType
{
Xml,
Binary,
}
class SerializerHelper
{
/// <summary>
/// Serialize the object to xml or binary file
/// </summary>
/// <typeparam name="T">the Type of the object</typeparam>
/// <param name="obj">it will be serialized object</param>
/// <returns>the operate result</returns>
public static void Serialize<T>(T obj, string filePath, SerializeType serializeType = SerializeType.Xml, ISurrogateSelector surrogate = null)
{
try
{
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
switch (serializeType)
{
case SerializeType.Xml:
using (StreamWriter fs = new StreamWriter(filePath, false, Encoding.UTF8))
{
XmlSerializer dataSerializer = new XmlSerializer(obj.GetType());
dataSerializer.Serialize(fs, obj);
}
break;
case SerializeType.Binary:
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.SurrogateSelector = surrogate;
formatter.Serialize(fs, obj);
}
break;
}
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
throw;
}
}
/// <summary>
/// DeSerialize file to the object
/// </summary>
/// <typeparam name="T">the Type of the object</typeparam>
/// <returns>the result value</returns>
public static T DeSerialize<T>(
string filePath,
SerializeType serializeType = SerializeType.Xml,
bool throwException = false,
ISurrogateSelector surrogate = null)
{
try
{
Trace.WriteLine(string.Format("Deserializing {0}.", filePath));
switch (serializeType)
{
case SerializeType.Xml:
using (StreamReader fs = new StreamReader(filePath, Encoding.UTF8))
{
XmlSerializer dataSerializer = new XmlSerializer(typeof(T));
return (T)dataSerializer.Deserialize(fs);
}
case SerializeType.Binary:
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.SurrogateSelector = surrogate;
return (T)formatter.Deserialize(fs);
}
default:
return default(T);
}
}
catch (Exception e)
{
if (throwException)
{
throw e;
}
else
{
Trace.WriteLine(string.Format("Deserialize {0} exception: {1}", filePath, e.Message));
return default(T);
}
}
}
}