使用Gzip对流进行压缩、解压缩
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.IO.Compression; namespace byteCompress { class Program { static void Main(string[] args) { Console.WriteLine("请输入文件的路径:"); string path = Console.ReadLine(); Console.WriteLine("文件路径:" + path); using (FileStream fileStream = new FileStream(path,FileMode.Open,FileAccess.Read, FileShare.Read)) { byte[] buffer = new byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); Console.WriteLine("原始的长度:" + buffer.Length); byte[] compressedBytes = GetCompressBytes(buffer); Console.WriteLine("压缩后的长度:" + compressedBytes.Length); byte[] decompressFiles = GetDecompressBytes(compressedBytes); Console.WriteLine("解压缩后的长度:" + decompressFiles.Length); bool isEqual = CompareData(decompressFiles, buffer); Console.WriteLine("解压缩后是否与原始的字节流相等:" + isEqual); } Console.ReadLine(); } /// <summary> /// 压缩字节流 /// </summary> /// <param name="originalBytes">原始字节流</param> /// <returns>压缩后的字节流</returns> private static byte[] GetCompressBytes(byte[] originalBytes) { MemoryStream memoryStream = new MemoryStream(); using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress)) { gzipStream.Write(originalBytes, 0, originalBytes.Length); } return memoryStream.ToArray(); } /// <summary> /// 解压缩字节流 /// </summary> /// <param name="compressedArray">压缩过的字节流</param> /// <returns>解压缩后的字节流</returns> private static byte[] GetDecompressBytes(byte[] compressedArray) { MemoryStream compressedstream = new MemoryStream(compressedArray); GZipStream decompressStream = new GZipStream(compressedstream, CompressionMode.Decompress); MemoryStream outStream = new MemoryStream(); CopyStream(decompressStream, outStream); return outStream.ToArray(); } /// <summary> /// 复制流,用于网络流、压缩流等无法获取长度的流 /// </summary> /// <param name="instream">网络流、压缩流等无法获取长度的流</param> /// <param name="outstream">可以获取长度的复制流</param> private static void CopyStream(Stream instream, Stream outstream) { const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = instream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } } /// <summary> /// 比较两个字节流是否相等 /// </summary> /// <param name="array1">字节流1</param> /// <param name="array2">字节流2</param> /// <returns>相等返回true,不相等返回false</returns> private static bool CompareData(byte[] array1, byte[] array2) { if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) return false; } return true; } } }
结果