You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

95 lines
2.8 KiB

using System.IO;
using System.Text;
using System.IO.Compression;
namespace Sog.IO
{
/// <summary>
/// zip压缩算法
/// </summary>
public static class ZipUtils
{
public static byte[] CompressString(string inputString)
{
byte[] input = Encoding.UTF8.GetBytes(inputString);
return CompressBytes(input);
}
public static byte[] CompressStringGZip(string inputString)
{
byte[] input = Encoding.UTF8.GetBytes(inputString);
return CompressBytesGzip(input);
}
public static byte[] CompressBytes(byte[] bytes)
{
var ms = new MemoryStream();
using (var cprs = new DeflateStream(ms, CompressionMode.Compress))
{
cprs.Write(bytes, 0, bytes.Length);
}
return ms.ToArray();
}
// size表示bytes的有效长度
public static byte[] CompressBytes(byte[] bytes, int size)
{
var ms = new MemoryStream();
using (var cprs = new DeflateStream(ms, CompressionMode.Compress))
{
cprs.Write(bytes, 0, size);
}
return ms.ToArray();
}
public static byte[] DecompressBytes(byte[] bytes)
{
return DecompressBytes(bytes, 0, bytes.Length);
}
public static byte[] DecompressBytes(byte[] bytes, int start, int length)
{
var ms = new MemoryStream(bytes, start, length);
var outms = new MemoryStream();
using (var deflateStream = new DeflateStream(ms, CompressionMode.Decompress, true))
{
var buf = new byte[1024];
int len;
while ((len = deflateStream.Read(buf, 0, buf.Length)) > 0)
{
outms.Write(buf, 0, len);
}
}
return outms.ToArray();
}
public static byte[] CompressBytesGzip(byte[] bytes)
{
var ms = new MemoryStream();
using (var cprs = new GZipStream(ms, CompressionMode.Compress))
{
cprs.Write(bytes, 0, bytes.Length);
}
return ms.ToArray();
}
public static byte[] DecompressBytesGzip(byte[] bytes)
{
var ms = new MemoryStream(bytes) { Position = 0 };
var outms = new MemoryStream();
using (var deflateStream = new GZipStream(ms, CompressionMode.Decompress, true))
{
var buf = new byte[1024];
int len;
while ((len = deflateStream.Read(buf, 0, buf.Length)) > 0)
{
outms.Write(buf, 0, len);
}
}
return outms.ToArray();
}
}
}