[压缩]C#下使用SevenZipSharp压缩解压文本
using SevenZip; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SLibrary { public class SevenZipUtil { /// <summary> /// 压缩字符串 /// </summary> /// <param name="input">源字符串</param> /// <returns>压缩后字节数组</returns> public static byte[] Compress(string input) { byte[] compressed = null; SevenZipCompressor compressor = new SevenZipCompressor(); compressor.CompressionMethod = CompressionMethod.Ppmd; compressor.CompressionLevel = CompressionLevel.High; using (MemoryStream msin = GetUTF8MemorySteam(input)) { using (MemoryStream msout = new MemoryStream()) { compressor.CompressStream(msin, msout); msout.Position = 0; compressed = new byte[msout.Length]; msout.Read(compressed, 0, compressed.Length); /* Console.WriteLine("compressed: "); foreach (byte b in compressed) { Console.Write(b); Console.Write(" "); } Console.WriteLine(); */ } } return compressed; } /// <summary> /// 获取输入字符串的UTF8编码 /// </summary> /// <param name="input">源字符串</param> /// <returns>内存数据流</returns> private static MemoryStream GetUTF8MemorySteam(string input) { MemoryStream ms = new MemoryStream(); byte[] bytes = Encoding.UTF8.GetBytes(input); ms.Write(bytes, 0, bytes.Length); return ms; } /// <summary> /// 解压字节数组 /// </summary> /// <param name="input">源字节数组</param> /// <returns>解压后字符串</returns> public static string Decompress(byte[] input) { /* Console.WriteLine("input:"); foreach (byte b in input) { Console.Write(b); Console.Write(" "); } Console.WriteLine(); */ byte[] uncompressedbuffer = null; using (MemoryStream msin = new MemoryStream()) { msin.Write(input, 0, input.Length); uncompressedbuffer = new byte[input.Length]; msin.Position = 0; using (SevenZipExtractor extractor = new SevenZipExtractor(msin)) { using (MemoryStream msout = new MemoryStream()) { extractor.ExtractFile(0, msout); msout.Position = 0; uncompressedbuffer = new byte[msout.Length]; msout.Read(uncompressedbuffer, 0, uncompressedbuffer.Length); } } } return Encoding.UTF8.GetString(uncompressedbuffer); } } }
Powered By D&J (URL:http://www.cnblogs.com/Areas/)