123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using System;
- using System.IO;
- using System.IO.Compression;
- using System.Text;
- namespace CSharpUtil
- {
- /// <summary>
- /// 压缩工具类
- /// </summary>
- class CompressUtil
- {
- /// <summary>
- /// 数据最大长度不宜超过1M
- /// </summary>
- const int MaxDataLenght = 1024 * 1024;
- /// <summary>
- /// 利用deflate算法压缩字节数组
- /// </summary>
- /// <param name="data">字节数组(不宜超过1M)</param>
- /// <param name="compressMode">压缩模式(压缩/解压)</param>
- /// <exception cref="OutOfMemoryException">数据不建议超过1M</exception>
- /// <returns></returns>
- public static byte[] Deflate(byte[] data, CompressionMode compressMode = CompressionMode.Compress)
- {
- if (data.Length > MaxDataLenght)
- {
- throw new OutOfMemoryException("传入的数据过大(不接受超过1M的数据)!");
- }
- else
- {
- byte[] buffer = null;
- using (MemoryStream outms = new MemoryStream())
- {
- using (DeflateStream df = new DeflateStream(outms, compressMode, true))
- {
- df.Write(data, 0, data.Length);
- }
- outms.Position = 0;
- buffer = outms.ToArray();
- }
- return buffer;
- }
- }
- /// <summary>
- /// 解压deflate数据
- /// </summary>
- /// <param name="data">被压缩的内容</param>
- /// <exception cref="OutOfMemoryException">数据不建议超过1M</exception>
- /// <returns></returns>
- public static byte[] InFlate(byte[] data)
- {
- // todo: 这种写法在system.io.compress模式下是支持的.
- return Deflate(data, CompressionMode.Decompress);
- }
- public static string InFlate(byte[] data, Encoding encoder)
- {
- using (MemoryStream inputStream = new MemoryStream(data))
- using (DeflateStream gzip = new DeflateStream(inputStream, CompressionMode.Decompress))
- using (StreamReader reader = new StreamReader(gzip, GlobalConfig.Encoding))
- {
- return reader.ReadToEnd();
- }
- }
- }
- }
|