压缩单个文件 ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize) { if (string.IsNullOrEmpty(fileToZip)) { throw new ArgumentNullException(fileToZip); } if (string.IsNullOrEmpty(zipedFile)) { throw new ArgumentNullException(zipedFile); } if (!File.Exists(fileToZip)) { + fileToZip + ); } try { using (var zipFile = File.Create(zipedFile)) { using (var zipStream = new ZipOutputStream(zipFile)) { using (var streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read)) { , StringComparison.Ordinal) + 1); var zipEntry = new ZipEntry(fileName); zipStream.PutNextEntry(zipEntry); zipStream.SetLevel(compressionLevel); var buffer = new byte[blockSize]; try { int sizeRead; do { sizeRead = streamToZip.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, sizeRead); } while (sizeRead > 0); } catch (Exception ex) { throw new Exception(ex.Message); } streamToZip.Close(); } zipStream.Finish(); zipStream.Close(); } zipFile.Close(); } } catch (IOException ioex) { throw new IOException(ioex.Message); } catch (Exception ex) { throw new Exception(ex.Message); } }
2. 压缩单个文件:压缩单个文件 ZipFile(string fileToZip, string zipedFile) { if (string.IsNullOrEmpty(fileToZip)) { throw new ArgumentException(fileToZip); } if (string.IsNullOrEmpty(zipedFile)) { throw new ArgumentException(zipedFile); } if (!File.Exists(fileToZip)) { + fileToZip + ); } try { using (var fs = File.OpenRead(fileToZip)) { var buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); using (var zipFile = File.Create(zipedFile)) { using (var zipStream = new ZipOutputStream(zipFile)) { , StringComparison.Ordinal) + 1); var zipEntry = new ZipEntry(fileName); zipStream.PutNextEntry(zipEntry); zipStream.SetLevel(5); zipStream.Write(buffer, 0, buffer.Length); zipStream.Finish(); zipStream.Close(); } } } } catch (IOException ioex) { throw new IOException(ioex.Message); } catch (Exception ex) { throw new Exception(ex.Message); } }
3.压缩多层目录:压缩多层目录 ZipFileDirectory(string strDirectory, string zipedFile) { if (string.IsNullOrEmpty(strDirectory)) { throw new ArgumentException(strDirectory); } if (string.IsNullOrEmpty(zipedFile)) { throw new ArgumentException(zipedFile); } using (var zipFile = File.Create(zipedFile)) { using (var s = new ZipOutputStream(zipFile)) { ZipSetp(strDirectory, s, ""); } } }
4.递归遍历目录: