压缩:
/// <summary> /// 把datatable数据转换成字节数组,然后压缩字节数组。 /// </summary> /// <param name="data">查询得到的数据表</param> /// <returns>返回被压缩的字节数组</returns> public static byte[] GzipCompress(DataTable data) { if (data == null || data.Rows.Count <= 0) return null; byte[] result = null; byte[] retbyte = null;//压缩后返回的字节数组 try { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, data); result = stream.GetBuffer(); } if (result != null) { using (MemoryStream stream = new MemoryStream()) { using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress)) { gZipStream.Write(result, 0, result.Length); gZipStream.Close(); } retbyte=stream.ToArray(); } } return retbyte; } catch (Exception) { return result; } }
public static byte[] GzipCompress(byte[] data)
{
if (data == null || data.Length < 1)
return data;
try
{
using (MemoryStream stream = new MemoryStream())
{
using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress))
{
gZipStream.Write(data, 0, data.Length);
gZipStream.Close();
}
return stream.ToArray();
}
}
catch (Exception)
{
return data;
}
}
byte[] retbyte = GzipCompress(retvalue); //retvalue为datatable
return Json(retbyte);
解压缩:
/// <summary> /// 解压数据。 /// </summary> /// <param name="ret">api中获取的结果,被压缩过的</param> public static DataTable DecompressByteToDatatble(string ret) { byte[] retbyte = JsonConvert.DeserializeObject<byte[]>(ret); //解压后得到的字节数组。 byte[] decBuffer = DecompressByte(retbyte); DataTable retdt = null; if (decBuffer != null && decBuffer.Length > 0) { using (MemoryStream memoryStream = new MemoryStream(decBuffer)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); retdt = (DataTable)binaryFormatter.Deserialize(memoryStream); } } return retdt; }
/// <summary>
/// 解压数据。
/// </summary>
/// <param name="ret">api中获取的结果,被压缩过的</param>
public static DataTable DecompressByteToDatatble(string ret)
{
byte[] retbyte = JsonConvert.DeserializeObject<byte[]>(ret);
//解压后得到的字节数组。
byte[] decBuffer = DecompressByte(retbyte);
DataTable retdt = null;
if (decBuffer != null && decBuffer.Length > 0)
{
using (MemoryStream memoryStream = new MemoryStream(decBuffer))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
retdt = (DataTable)binaryFormatter.Deserialize(memoryStream);
}
}
return retdt;
}
ds = DecompressByteToDatatble(ret); //ret为取到的json