很神奇的一个类,不用序列化到文件中,只序列化到字符串里,然后再反序列出来 ,刚从网上找到,分享一下
public class SerializeUtilities
{
public SerializeUtilities()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 序列化 对象到字符串
/// </summary>
/// <param name="obj">泛型对象</param>
/// <returns>序列化后的字符串</returns>
public static string Serialize<T>(T obj)
{
try
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Flush();
stream.Close();
return Convert.ToBase64String(buffer);
}
catch (Exception ex)
{
throw new Exception("序列化失败,原因:" + ex.Message);
}
}
public static T Desrialize<T>(T obj, string str)
{
try
{
obj = default(T);
IFormatter formatter = new BinaryFormatter();
byte[] buffer = Convert.FromBase64String(str);
MemoryStream stream = new MemoryStream(buffer);
obj = (T)formatter.Deserialize(stream);
stream.Flush();
stream.Close();
}
catch (Exception ex)
{
throw new Exception("反序列化失败,原因:" + ex.Message);
}
return obj;
}
}