C#之数据流和字符串压缩

10 篇文章 3 订阅

.Net自带的类库,System.IO.Compress中自带GZip压缩。


using System;
using System.IO;
using System.IO.Compression;
using System.Text;

public class GZipUtil {

	/// <summary>  
	/// 字节数组压缩  
	/// </summary>  
	/// <param name="strSource"></param>  
	/// <returns></returns>  
	public static byte[] Compress(byte[] data)  
	{  
		try  
		{  
			MemoryStream ms = new MemoryStream();  
			GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);  
			zip.Write(data, 0, data.Length);  
			zip.Close();  
			byte[] buffer = new byte[ms.Length];  
			ms.Position = 0;  
			ms.Read(buffer, 0, buffer.Length);  
			ms.Close();  
			return buffer;  

		}  
		catch (Exception e)  
		{  
			throw new Exception(e.Message);  
		}  
	} 
	/// <summary>  
	/// 字节数组解压缩  
	/// </summary>  
	/// <param name="strSource"></param>  
	/// <returns></returns>  
	public static byte[] Decompress(byte[] data)  
	{  
		try  
		{  
			MemoryStream ms = new MemoryStream(data);  
			GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);  
			MemoryStream msreader = new MemoryStream();  
			byte[] buffer = new byte[0x1000];  
			while (true)  
			{  
				int reader = zip.Read(buffer, 0, buffer.Length);  
				if (reader <= 0)  
				{  
					break;  
				}  
				msreader.Write(buffer, 0, reader);  
			}  
			zip.Close();  
			ms.Close();  
			msreader.Position = 0;  
			buffer = msreader.ToArray();  
			msreader.Close();  
			return buffer;  
		}  
		catch (Exception e)  
		{  
			throw new Exception(e.Message);  
		}  
	}  

	/// <summary>
	/// 字符串压缩
	/// </summary>
	/// <returns>The string.</returns>
	/// <param name="str">String.</param>
	public static string CompressString(string str)  
	{  
		string compressString = "";  
		byte[] compressBeforeByte = Encoding.UTF8.GetBytes(str);  
		byte[] compressAfterByte = Compress(compressBeforeByte);  
		//compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);    
		compressString = Convert.ToBase64String(compressAfterByte);  
		return compressString;  
	}  
	/// <summary>
	/// 字符串解压缩
	/// </summary>
	/// <returns>The string.</returns>
	/// <param name="str">String.</param>
	public static string DecompressString(string str)  
	{  
		string compressString = "";  
		//byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);    
		byte[] compressBeforeByte = Convert.FromBase64String(str);  
		byte[] compressAfterByte = Decompress(compressBeforeByte);  
		compressString = Encoding.UTF8.GetString(compressAfterByte);  
		return compressString;  
	}  
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值