c#压缩和解压缩
项目上用到的,随手做个记录,哈哈。
直接上代码:
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Collections.Generic;
5 using System.IO;
6 using ICSharpCode.SharpZipLib.Zip;
7 using ICSharpCode.SharpZipLib.Checksums;
8 namespace BLL
9 {
10 /// <summary>
11 /// 文件(夹)压缩、解压缩
12 /// </summary>
13 public class FileCompression
14 {
15 #region 压缩文件
16 /// <summary>
17 /// 压缩文件
18 /// </summary>
19 /// <param name="fileNames">要打包的文件列表</param>
20 /// <param name="GzipFileName">目标文件名</param>
21 /// <param name="CompressionLevel">压缩品质级别(0~9)</param>
22 /// <param name="deleteFile">是否删除原文件</param>
23 public static void CompressFile(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, bool deleteFile)
24 {
25 ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
26 try
27 {
28 s.SetLevel(CompressionLevel); //0 - store only to 9 - means best compression
29 foreach (FileInfo file in fileNames)
30 {
31 FileStream fs = null;
32 try
33 {
34 fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
35 }
36 catch
37 { continue; }
38 // 方法二,将文件分批读入缓冲区
39 byte[] data = new byte[2048];
40 int size = 2048;
41 ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
42 entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
43 s.PutNextEntry(entry);
44 while (true)
45 {
46 size = fs.Read(data, 0, size);
47 if (size <= 0) break;
48 s.Write(data, 0, size);
49 }
50 fs.Close();
51 if (deleteFile)
52 {
53 file.Delete();
54 }
55 }
56 }
57 finally
58 {
59 s.Finish();
60 s.Close();
61 }
62 }
63 /// <summary>
64 /// 压缩文件夹
65 /// </summary>
66 /// <param name="dirPath">要打包的文件夹</param>
67 /// <param name="GzipFileName">目标文件名</param>
68 /// <param name="CompressionLevel">压缩品质级别(0~9)</param>
69 /// <param name="deleteDir">是否删除原文件夹</param>
70 public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
71 {
72 //压缩文件为空时默认与压缩文件夹同一级目录
73 if (GzipFileName == string.Empty)
74 {
75 GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + 1);
76 GzipFileName = dirPath.Substring(0, dirPath.LastIndexOf("//")) + "