C# helper Class
/// <summary>
/// 二进制序列化,带压缩
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string BinarySerialize(object obj)
{
string ret = string.Empty;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
MemoryStream msZip = new MemoryStream();
GZipStream gZip = new GZipStream(msZip, CompressionMode.Compress);
byte[] aryByte = ms.ToArray();
gZip.Write(ms.ToArray(), 0, aryByte.Length);
aryByte = null;
ret = Convert.ToBase64String(msZip.ToArray());
gZip.Close();
msZip.Close();
ms.Close();
return ret;
}
/// <summary>
/// 二进制反序列化,带压缩
/// </summary>
/// <param name="binaryString"></param>
/// <returns></returns>
public static object BinaryDeserialize(string binaryString)
{
object obj = null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream msZip = new MemoryStream(Convert.FromBase64String(binaryString));
GZipStream gZip = new GZipStream(msZip, CompressionMode.Decompress);
MemoryStream ms = new MemoryStream();
int n;
byte[] bytes = new byte[2000];//一次最多读取2000字节
while ((n = gZip.Read(bytes, 0, bytes.Length)) != 0)
{
ms.Write(bytes, 0, n);
}
string all = Encoding.Default.GetString(ms.ToArray());
ms.Seek(0, SeekOrigin.Begin);
obj = bf.Deserialize(ms);
gZip.Close();
msZip.Close();
ms.Close();
bytes = null;
return obj;
}
/// <summary>
/// dataTable transfer DTO
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static T GetEntity<T>(DataTable table) where T : new()
{
T entity = new T();
foreach (DataRow row in table.Rows)
{
foreach (var item in entity.GetType().GetProperties())
{
if (row.Table.Columns.Contains(item.Name))
{
if (DBNull.Value != row[item.Name])
{
item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
}
}
}
}
return entity;
}
/// <summary>
/// dataTable transfer DTOList
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static IList<T> GetEntities<T>(DataTable table) where T : new()
{
IList<T> entities = new List<T>();
foreach (DataRow row in table.Rows)
{
T entity = new T();
foreach (var item in entity.GetType().GetProperties())
{
item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
}
entities.Add(entity);
}
return entities;
}