/**//// <summary> /// 以Zip格式压缩指定文件 /// </summary> /// <param name="源文件">要压缩的文件路径</param> /// <param name="目标文件">压缩后保存的文件路径</param> public static void 压缩文件(string 源文件, string 目标文件) ...{ if (!File.Exists(源文件)) throw new FileNotFoundException(); using (FileStream sourceStream = new FileStream(源文件, 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(目标文件, FileMode.OpenOrCreate, FileAccess.Write)) ...{ using (GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true)) ...{ compressedStream.Write(buffer, 0, buffer.Length); } } } } /**//// <summary> /// 解压缩指定的Zip文件 /// </summary> /// <param name="源文件">要解压缩的文件路径</param> /// <param name="目标文件">解压缩后保存的文件路径</param> public static void 解压缩文件(string 源文件, string 目标文件) ...{ if (!File.Exists(源文件)) throw new FileNotFoundException(); using (FileStream sourceStream = new FileStream(源文件, 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(目标文件, FileMode.Create)) ...{ destinationStream.Write(buffer, 0, total); destinationStream.Flush(); } } } }