[图片]using System;
[图片]using System.IO;
[图片]using System.IO.Compression;
[图片][图片]namespace Skyiv.Helper
[图片][图片][图片]{
[图片] static class Zip
[图片][图片] [图片]{
[图片] public static void CompressFile(string sourceFile, string destinationFile)
[图片][图片] [图片]{
[图片] if (!File.Exists(sourceFile)) throw new FileNotFoundException();
[图片] using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
[图片][图片] [图片]{
[图片] byte [] buffer = new byte[sourceStream.Length];
[图片] int checkCounter = sourceStream.Read(buffer, 0, buffer.Length);
[图片] if (checkCounter != buffer.Length) throw new ApplicationException();
[图片] using (FileStream destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write))
[图片][图片] [图片]{
[图片] using (GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true))
[图片][图片] [图片]{
[图片] compressedStream.Write(buffer, 0, buffer.Length);
[图片] }
[图片] }
[图片] }
[图片] }
[图片] [图片] public static void DecompressFile(string sourceFile, string destinationFile)
[图片][图片] [图片]{
[图片] if (!File.Exists( sourceFile)) throw new FileNotFoundException();
[图片] using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open))
[图片][图片] [图片]{
[图片] byte [] quartetBuffer = new byte[4];
[图片] int position = (int)sourceStream.Length - 4;
[图片] sourceStream.Position = position;
[图片] sourceStream.Read(quartetBuffer, 0, 4);
[图片] sourceStream.Position = 0;
[图片] int checkLength = BitConverter.ToInt32(quartetBuffer, 0);
[图片] byte[] buffer = new byte[checkLength + 100];
[图片] using (GZipStream decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true))
[图片][图片] [图片]{
[图片] int total = 0;
[图片] for (int offset = 0; ; )
[图片][图片] [图片]{
[图片] int bytesRead = decompressedStream.Read(buffer, offset, 100);
[图片] if (bytesRead == 0) break;
[图片] offset += bytesRead;
[图片] total += bytesRead;
[图片] }
[图片] using (FileStream destinationStream = new FileStream(destinationFile, FileMode.Create))
[图片][图片] [图片]{
[图片] destinationStream.Write(buffer, 0, total);
[图片] destinationStream.Flush();
[图片] }
[图片] }
[图片] }
[图片] }
[图片] }
[图片]}
[图片]
运行结果如下: