using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Ant.Frame
{
public static class Serialization
{
#region 对实体类进行序列化和反序列化
///
/// 将对象序列化
///
///
///
private static MemoryStream Serialize(object obj)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, obj);
return ms;
}
catch
{
return null;
}
}
///
///
///
///
///
///
private static Stream Serialize(object obj, Stream stream)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
return stream;
}
catch
{
return null;
}
}
///
/// 序列化
///
///
///
private static object Deserialize(Stream stream)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}
catch
{
return null;
}
}
///
/// 将实体或datatable转换为string
///
///
///
public static string SerializeToString(object obj)
{
try
{
MemoryStream msObj = Serialize(obj);
return Convert.ToBase64String(msObj.ToArray());
}
catch
{
return null;
}
}
///
/// 将string转换为对象
///
///
///
public static object DeserializeFromString(string str)
{
try
{
byte[] byteArrayObj = Convert.FromBase64String(str);
Stream myObj = new MemoryStream(byteArrayObj);
return Deserialize(myObj);
}
catch
{
return null;
}
}
#endregion
}
}