c#压缩数据传输的代码一例

发布时间:2020-01-25编辑:脚本学堂
用c#实现简单的数据压缩传递,减少带宽占用,提高访问速度,有需要的朋友,可以参考下。

代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
using System.Text;

namespace Common
{
 /// <summary>
 /// 压缩数据传输
 /// http://www.jb200.com
 /// </summary>
 public class UnZip
 {
  public UnZip()
  {
  }

  #region 返回压缩后的字节数组
  /// <summary>
  /// 返回压缩后的字节数组
  /// </summary>
  /// <param name="data"></param>
  /// <returns></returns>
  public static byte[] Compress(byte[] data)
  {
   if (data == null || data.Length == 0)
   {
    return null;
   }

   MemoryStream inStream = new MemoryStream(data, 0, data.Length);
   MemoryStream outStream = new MemoryStream();
   BZip2.Compress(inStream, outStream,false, data.Length);

   byte[] result = outStream.ToArray();
   inStream.Close();
   outStream.Close();

   return result;
  }
  #endregion

  #region 返回解压后的字节数组
  /// <summary>
  /// 返回解压后的字节数组
  /// </summary>
  /// <param name="data">原始字节数组</param>
  /// <returns></returns>
  public static byte[] Decompress(byte[] data)
  {
   if (data == null || data.Length == 0)
   {
    return null;
   }
   MemoryStream inStream = new MemoryStream(data, 0, data.Length);
   MemoryStream outStream = new MemoryStream();
   BZip2.Decompress(inStream, outStream,false);
   
   byte[] result = outStream.ToArray();
   inStream.Close();
   outStream.Close();

   return result;
  }

  #endregion
 }
}