123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- 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 对实体类进行序列化和反序列化
- /// <summary>
- /// 将对象序列化
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- private static MemoryStream Serialize(object obj)
- {
- try
- {
- BinaryFormatter formatter = new BinaryFormatter();
- MemoryStream ms = new MemoryStream();
- formatter.Serialize(ms, obj);
- return ms;
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="obj"></param>
- /// <param name="stream"></param>
- /// <returns></returns>
- private static Stream Serialize(object obj, Stream stream)
- {
- try
- {
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(stream, obj);
- return stream;
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- /// 序列化
- /// </summary>
- /// <param name="stream"></param>
- /// <returns></returns>
- private static object Deserialize(Stream stream)
- {
- try
- {
- BinaryFormatter formatter = new BinaryFormatter();
- return formatter.Deserialize(stream);
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- /// 将实体或datatable转换为string
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string SerializeToString(object obj)
- {
- try
- {
- MemoryStream msObj = Serialize(obj);
- return Convert.ToBase64String(msObj.ToArray());
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- /// 将string转换为对象
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static object DeserializeFromString(string str)
- {
- try
- {
- byte[] byteArrayObj = Convert.FromBase64String(str);
- Stream myObj = new MemoryStream(byteArrayObj);
- return Deserialize(myObj);
- }
- catch
- {
- return null;
- }
- }
- #endregion
- }
- }
|